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

时间:2018-08-07 12:11:58

标签: python matplotlib

我有两个价格不同的清单。第一个是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()

5 个答案:

答案 0 :(得分:6)

我建议您简单地为每组点定义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()

答案 1 :(得分:3)

要告诉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')

答案 2 :(得分:2)

您应该创建一个包含您的年份的新列表。 然后,您可以通过例如odoing years [10:18]指定要在x轴上绘制的位置

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轴

答案 3 :(得分:1)

IIUC,只需用{{ \Carbon\Carbon::parse($data['date'])->diffForHumans() }} / None填补您的失踪年份:

NaN

plot

答案 4 :(得分:0)

有很多方法可以实现这一目标。一种优雅的方法是使用熊猫。这样,您将自动获得正确标记并对齐的x刻度。

from matplotlib import pyplot as plt
import pandas as pd

geb_b30_x = pd.date_range(start="20080101", end="20180101", freq="A")
geb_b30_y = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
geb_b30 = pd.Series(data=geb_b30_y, index=geb_b30_x)

geb_a30_x = pd.date_range(start="20100101", end="20180101", freq="A")
geb_a30_y = [12, 10, 13, 14, 12, 13, 18, 16]
geb_a30 = pd.Series(data=geb_a30_y, index=geb_a30_x)

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()
相关问题