如何将Matplotlib plot中的xaxis设置为完全跟随数据帧索引?

2024-04-19 16:16:09 发布

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

我在画一个图,我想把从多个数据帧绘制出来的几条线放到同一个x-y空间。我通过以下代码成功实现了这一点:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.plot(simulation_cycles_geomean_df1, 'g', label = 'Scheduler = SDC, Max Chain Delay = 0.9')    # We can feed a DataFrame object as input directly to matplotlib since DataFrame is based on Numpy array object
ax.plot(simulation_cycles_geomean_df2, 'r', label = 'Scheduler = SDC, Max Chain Delay = 1000.9')
ax.plot(simulation_cycles_geomean_df3, 'b', label = 'Scheduler = List, Max Chain Delay = 0.9')
ax.plot(simulation_cycles_geomean_df4, 'y', label = 'Scheduler = List, Max Chain Delay = 1000.9')

ax.legend(loc = 'best')
fig.savefig('combined_plot.pdf')

其中一个DataFrame对象,比如simulation_cycles_geomean_df1,看起来像:

^{pr2}$

我可以使用上面的绘图语句得到下图(由于我的数据框中有NaN值,所以行中的分隔符是可以的):

enter image description here

但是正如您在x轴上看到的,这些值并不是完全按1300, 1301, 1302 ... 1344来的,而是从0开始。有人知道如何设置Matplotlib使x轴完全跟随数据帧的build_number索引吗?在

我想问的另一个问题是,看看这个数字,你会发现这个传说不可避免地很大,它覆盖了一些图表。有人知道我怎么把传说移到某个地方,或者我能做的任何事情,这样它就不会覆盖任何一行了吗?在

非常感谢。在


Tags: 数据chaindataframeplotfigaxlabelmax
1条回答
网友
1楼 · 发布于 2024-04-19 16:16:09

下面是一个带有虚拟数据帧的示例。数据如下:

my_index    count
49         9320.0
50         9418.0
51        10490.0
52         7376.0
53         5018.0

首先,确保您想要在x轴上的标签是数据帧的索引。然后,使用pandas dataframe的plot()函数,它就像charm一样工作。在

^{pr2}$

情节现在是这样的: enter image description here

关于第二个答案,可以使用plt.图例(). 在

dummy_data.plot(legend=True)
plt.legend(loc='upper left', bbox_to_anchor=(1, 0.5),fancybox = True)

情节现在是这样的: enter image description here

其他有效的“loc”选项是:[上中心,中间,左下,左中,右,右中,右上,右下,左上,中,最佳]。试试看哪一种最适合你。在

相关问题 更多 >