我想预先绘制xaxis,使其包含5年,即2012,2013,2014,2015和2016.然后说我有两组数据,第一组是两个列表:
years1 = ['2012','2013']
scores1 = [0.2,0.3]
第二个也是两个列表,但与第一个列表的长度不同:
years2 = ['2013','2014','2015']
scores2 = [0.5,-0.4,0.8]
如何在python中使用matplotlib在一个图中绘制这两组数据? x轴是预定的。
答案 0 :(得分:1)
您只需拨打分散两次:
import matplotlib.pyplot as plt
years1_string = ['2012','2013']
years2_string = ['2013','2014','2015']
years1 = [int(i) for i in years1_string]
scores1 = [0.2,0.3]
years2 = [int(i) for i in years2_string]
scores2 = [0.5,-0.4,0.8]
fig, ax = plt.subplots(1)
ax.set_xlim(2012,2016)
ax.set_xticks([2012,2013,2014,2015,2016])
ax.scatter(years1, scores1, c='r', edgecolor=None, label = 'One')
ax.scatter(years2, scores2, c='b', edgecolor=None, label = 'Two')
ax.legend()
fig.show()
答案 1 :(得分:0)
您不必预先确定xaxis。它会自动调整数据。如果您不想要,您当然可以手动设置限制或滴答。
然后,您可以将字符串转换为整数以进行绘图:
import matplotlib.pyplot as plt
years1 = ['2012','2013']
scores1 = [0.2,0.3]
years2 = ['2013','2014','2015']
scores2 = [0.5,-0.4,0.8]
#convert string list to integer list
y1 = list(map(int, years1))
y2 = list(map(int, years2))
plt.plot(y1, scores1, marker="o")
plt.plot(y2, scores2, marker="o")
plt.xticks(y1+y2)
plt. show()
但是,matplotlib可以很好地绘制字符串,只要它们可以转换为有意义的数字或日期。所以以下工作也很好。
import matplotlib.pyplot as plt
years1 = ['2012','2013']
scores1 = [0.2,0.3]
years2 = ['2013','2014','2015']
scores2 = [0.5,-0.4,0.8]
plt.plot(years1, scores1, marker="o")
plt.plot(years2, scores2, marker="o")
plt.xticks(range(2012,2016))
plt. show()