matplotlib 带有共享日期时间色条的散点图

13z8s7eq  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(121)

我想绘制一个基于经度和纬度的散点图。散点图的大小取决于另一个值“LF”。

longitude = df['evlo']
latitude = df['evla']
lf = df['LF']

# Define the size based on the LF values
size = lf

还有另一个包含日期信息的列,我将其转换为日期时间格式:

df['dates'] = pd.to_datetime(df['fold'].str[0:8], format='%Y%m%d')

df['dates'] = df['dates'].dt.strftime('%Y-%m-%d')

输出格式如下:
我想用一个共享的彩条以15天的间隔绘制散点子图。我已经做了这项工作,但似乎每个子图都有自己的彩条,例如蓝色和红色存在于每个子图中,这不应该在真实的情况下。下面是我的尝试:

`import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
import matplotlib.cm as cm
import matplotlib.colors as colors

# Filter data based on LF values

df_lf_more_than_1 = df[df['LF'] > 1]

# Get the minimum and maximum dates in the filtered data
min_date = df_lf_more_than_1['dates'].min()
max_date = df_lf_more_than_1['dates'].max()

# Create a figure with four subplots
fig, axes = plt.subplots(2, 2, figsize=(12, 10),sharex=True, sharey=True)
axes = axes.flatten()    
for i, ax in enumerate(axes):
    # Calculate the start and end dates for the current interval
    start_date = min_date + pd.DateOffset(days=i * 15)
    end_date = start_date + pd.DateOffset(days=14)

    
    # Filter the data for the current interval
    df_interval = df_lf_more_than_1[(df_lf_more_than_1['dates'] >= start_date)
                                    & (df_lf_more_than_1['dates'] <= end_date)]
    # Plot the scatter plot for the current interval
    scatter = ax.scatter(df_interval['evlo'], df_interval['evla'], 
                         s=df_interval['LF']*5,
                         c=mdates.date2num(df_interval['dates']), cmap='jet')
        
 
    # Set the title of the subplot to the start and end dates
    ax.set_title(f'Interval: {start_date.strftime("%Y-%m-%d")} - {end_date.strftime("%Y-%m-%d")}')

    ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.2f'))
        

cax = fig.add_axes([0.15, 0.05, 0.7, 0.03])  # Position of the colorbar
cbar = fig.colorbar(cm.ScalarMappable(norm=norm, cmap='jet'), cax=cax, orientation='horizontal')

plt.subplots_adjust(bottom=0.09)

plt.show()`

o3imoua4

o3imoua41#

我相信这是因为你在散点图中没有指定vminvmax。如果你没有指定数据范围,那么整个色图范围将被用来覆盖数据。请参见描述here。如果你为每个图制作单独的颜色条,你可以看到这一点:

from matplotlib import pyplot as plt
import numpy as np

# two subplots
fig, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2, figsize = (7, 3))
fig.suptitle("Not specifying vmin and vmax")

# plotting two plots with different time ranges
for ax, t1, t2 in zip([ax1, ax2], [0, 5], [5, 10]):
    longitude = np.random.uniform(10, 20, 50)
    latitude = np.random.uniform(50, 60, 50)
    t = np.linspace(t1, t2, 50)

    tmp = ax.scatter(x = longitude, y = latitude, c = t, cmap = "jet")
    plt.colorbar(tmp, ax = ax)

plt.show()

这就产生了这样的图,其中颜色范围对于两者是相同的,但是值是不同的。

如果您为所有子图指定相同的数据范围,例如初始和最终时间步长,则所有点将根据相同的颜色范围着色。在示例中,全范围是从0到10。

tmp = ax.scatter(x = longitude, y = latitude, c = t, cmap = "jet", vmin = 0, vmax = 10)

这产生了这个图:

每个颜色条上的值相同,并且点按相同的比例着色。
因此,要使共享色条有意义,您需要确保色图的数据范围由所有子图共享,并且该数据范围对应于数据中的初始和最终时间步长。

相关问题