使用设置标签和图例plt.子批次()

2024-09-28 19:06:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用小批要创建一个包含12个子图的地物,这些子图共享相同的数据,所以我要显示其中一个子图的标签和图例。我正在从一个包含pandas数据帧的字典中访问和绘制数据,每个数据帧有20列(标签)。这里是我的代码:

fig, axes = plt.subplots(nrows=3, ncols=4, sharex=True, sharey=True)
plt.subplots_adjust(left = 0.06, bottom = 0.1, right = 0.8, top=0.9, 
wspace=0.15, hspace=0.15)
fig.suptitle('HMC Water Balance', fontsize = 20, y= 0.95, x=0.45)

axes[0,0].plot(HMC_hydrographs['outlet'])
axes[0,1].plot(HMC_hydrographs['Outlet00'])
axes[0,2].plot(HMC_hydrographs['Outlet01'])
axes[0,3].plot(HMC_hydrographs['Outlet02'], label = 
'Q_total','Q_reset','Q_river_initial', ...'20th_column_name')
ax = axes[0,3]
ax.legend(loc=0, prop={'size':8})
axes[1,0].plot(HMC_hydrographs['Outlet03'])
ax = axes[1,0]
ax.set_ylabel('Flux (m$^3$/s)', labelpad=10, fontsize = 18)
axes[1,1].plot(HMC_hydrographs['Outlet04'])
axes[1,2].plot(HMC_hydrographs['Outlet05'])
axes[1,3].plot(HMC_hydrographs['Outlet06'])
axes[2,0].plot(HMC_hydrographs['Outlet07'])
axes[2,1].plot(HMC_hydrographs['Outlet08'])
ax = axes[2,1]
ax.set_xlabel('Time (days)', fontsize = 18)
ax.xaxis.set_label_coords(1.1,-0.2)
axes[2,2].plot(HMC_hydrographs['Outlet09'])
axes[2,3].plot(HMC_hydrographs['Outlet10'])

我得到了一个错误:

^{pr2}$

据我所知,label参数只接受一个参数,但我有多个label!在

请帮助我理解如何调用标签,以便在绘制单个图形时显示如下:

fig = plt.figure()
ax = HMC_hydrographs['Outlet01'].plot()

Individual plot showing the correct labels


Tags: 数据trueplotfig绘制plt标签ax
1条回答
网友
1楼 · 发布于 2024-09-28 19:06:12

我不确定它背后的原因,但我设法让图例显示的方法是直接在图例参数中指定标签,而不是使用“label”参数。代码如下:

fig, axes = plt.subplots(nrows=3, ncols=4, sharex=True, sharey=True)
plt.subplots_adjust(left = 0.06, bottom = 0.1, right = 0.8, top=0.9, 
wspace=0.15, hspace=0.15)
fig.suptitle('HMC Water Balance', fontsize = 20, y= 0.95, x=0.45)
axes[0,0].plot(HMC_hydrographs['outlet'])
axes[0,1].plot(HMC_hydrographs['Outlet00'])
axes[0,2].plot(HMC_hydrographs['Outlet01'])
axes[0,3].plot(HMC_hydrographs['Outlet02'])
ax = axes[0,3]
ax.legend(hydro_header, bbox_to_anchor=(1.05, 1), loc=2, 
borderaxespad=0.)
axes[1,0].plot(HMC_hydrographs['Outlet03'])
ax = axes[1,0]
ax.set_ylabel('Flux (m$^3$/s)', labelpad=10, fontsize = 18)
axes[1,1].plot(HMC_hydrographs['Outlet04'])
axes[1,2].plot(HMC_hydrographs['Outlet05'])
axes[1,3].plot(HMC_hydrographs['Outlet06'])
axes[2,0].plot(HMC_hydrographs['Outlet07'])
axes[2,1].plot(HMC_hydrographs['Outlet08'])
ax = axes[2,1]
ax.set_xlabel('Time (days)', fontsize = 18)
ax.xaxis.set_label_coords(1.1,-0.2)
axes[2,2].plot(HMC_hydrographs['Outlet09'])
axes[2,3].plot(HMC_hydrographs['Outlet10'])

hydro_header包含一个列表,其中包含我使用以下方法获得的绘图的列名(标签):

^{pr2}$

Final figure with the subplots and legend

相关问题 更多 >