Python 如何在Matplotlib plot中设置x轴以精确跟随数据帧索引?
我正在绘制一个图,在这个图中,我想将多个数据帧中绘制的几条线放在同一个x-y空间中。我通过以下代码实现了这一点:Python 如何在Matplotlib plot中设置x轴以精确跟随数据帧索引?,python,matplotlib,pandas,plot,Python,Matplotlib,Pandas,Plot,我正在绘制一个图,在这个图中,我想将多个数据帧中绘制的几条线放在同一个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 direct
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')
其中一个数据帧对象,例如模拟\u循环\u geomean\u df1
,如下所示:
In [76]: data_analysis.simulation_cycles_geomean_df1 # data_analysis is the module that contains the source code
Out[76]:
cycles
build_number
1300 4932.788490
1301 4967.047532
1302 4968.503010
1303 4966.810638
1304 4964.470973
...
...
...
# And so on... until 1344
my_index count
49 9320.0
50 9418.0
51 10490.0
52 7376.0
53 5018.0
我可以使用上面的绘图状态得到下图(行中的中断是正常的,因为我的数据框中有NaN
值):
但正如你在x轴上所看到的,这些值并不完全符合13001302。。。1344,但从0开始。有人知道我如何设置Matplotlib,使x轴精确地跟随数据帧的构建编号
索引吗
我想问的另一个问题是,看看这个图,你可以看到这个图例不可避免地很大,它涵盖了一些图表。有人知道我怎样才能把传说移到某个地方,或者我能做的任何事情,使它不覆盖任何一行吗
非常感谢。这里是一个带有虚拟数据帧的示例。数据如下所示:
In [76]: data_analysis.simulation_cycles_geomean_df1 # data_analysis is the module that contains the source code
Out[76]:
cycles
build_number
1300 4932.788490
1301 4967.047532
1302 4968.503010
1303 4966.810638
1304 4964.470973
...
...
...
# And so on... until 1344
my_index count
49 9320.0
50 9418.0
51 10490.0
52 7376.0
53 5018.0
首先,确保x轴上需要的标签是数据帧的索引。然后,使用pandas dataframe的plot()函数,它的工作原理很好
dummy_data.plot()
现在的情节是这样的:
关于第二个答案,可以使用plt.legend()移动图例
现在的情节是这样的:
其他有效的“loc”选项有:[中上、中、左下、左中、右、右中、右上、右下、左上、中下、最佳]。试着看看哪一个最适合你。你应该能够使用模拟\u循环\u geomean\u df1.plot(ax=ax)
,它会工作的。否则,ax.plot(simulation\u cycles\u geomean\u df1.index,simulation\u cycles\u geomean\u df1)
应该可以做到。ax.plot(simulation\u cycles\u geomean\u df1.index,simulation\u cycles\u geomean\u df1)
工作得很好。谢谢@tomaugsurger!除了这个问题,你知道我如何定位图例,使其不覆盖任何线条吗?