Python绘制两个长度不同的列表

2024-09-28 20:53:04 发布

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

我有两张不同价格的单子。第一份名单是2008-2018年,第二份是2010-2018年。在2008年至2018年在X轴上,第二个列表从2010年开始的情况下,我如何绘制它们?在

下面是简短代码的示例:

from matplotlib import pyplot as plt

Geb_b30 = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
Geb_a30 = [12, 10, 13, 14, 12, 13, 18, 16]

fig, ax = plt.subplots()
ax.plot(Geb_b30, label='Prices 2008-2018', color='blue')
ax.plot(Geb_a30, label='Prices 2010-2018', color = 'red')
legend = ax.legend(loc='center right', fontsize='x-large')
plt.xlabel('years')
plt.ylabel('prices')
plt.title('Comparison of the different prices')
plt.show()

Tags: 列表plotplt价格axlabel单子color
3条回答

你应该创建一个新的清单,上面写着你的年龄。 然后,你可以指定你想在x轴上绘制的位置,例如用odoing years[10:18]来绘制

from matplotlib import pyplot as plt

Geb_b30 = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
Geb_a30 = [12, 10, 13, 14, 12, 13, 18, 16]

years = list(range(2008,2018))

fig, ax = plt.subplots()
ax.plot(years[0:len(Geb_b30)],Geb_b30, label='Prices 2008-2018', 
color='blue')
ax.plot(years[2:],Geb_a30, label='Prices 2010-2018', color = 
'red')
legend = ax.legend(loc='center right', fontsize='x-large')
plt.xlabel('years')
plt.ylabel('prices')
plt.title('Comparison of the different prices')
plt.show()

编辑:用正确的x轴更新

要告诉matplotlib希望点在x轴上的结束位置,必须显式提供x值。x轴值的大小必须与y值的大小相对应,但是独立数据集之间不需要有任何关系,正如您已经看到的那样。在

Geb_x = range(2008, 2018)

...

ax.plot(Geb_x, Geb_b30, label='Prices 2008-2018', color='blue')
ax.plot(Geb_x[2:], Geb_a30, label='Prices 2010-2018', color = 'red')

我建议您只需为每组点定义x值(即年份列表),并将它们传递到ax.plot()的参数中,如下所示:

from matplotlib import pyplot as plt

Geb_b30 = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
years_b30 = range(2008,2018)
Geb_a30 = [12, 10, 13, 14, 12, 13, 18, 16]
years_a30 = range(2010,2018)

fig, ax = plt.subplots()
ax.plot(years_b30, Geb_b30, label='Prices 2008-2018', color='blue')
ax.plot(years_a30, Geb_a30, label='Prices 2010-2018', color = 'red')
legend = ax.legend(loc='center right', fontsize='x-large')
plt.xlabel('years')
plt.ylabel('prices')
plt.title('Comparison of the different prices')
plt.show()

相关问题 更多 >