简体   繁体   English

在matplotlib中绘制数据之前在xaxis上绘制年份

[英]Plot year on xaxis before plot data in matplotlib

I want to pre plot xaxis so that it contains 5 years, which are 2012,2013,2014,2015 and 2016. Then say I have two sets of data, first one is two list: 我想预先绘制xaxis的图,使其包含5年,分别是2012、2013、2014、2015和2016。然后说我有两组数据,第一个是两个列表:

years1 = ['2012','2013']
scores1 = [0.2,0.3]

second one is also two lists, but has different length from the first one: 第二个也是两个列表,但是长度与第一个不同:

years2 = ['2013','2014','2015']
scores2 = [0.5,-0.4,0.8]

How can I plot these two sets of data in one plot, using matplotlib in python? 如何使用python中的matplotlib在一个图中绘制这两套数据? The xaxis is predetermined. x轴是预定的。

You can just call scatter twice: 您可以只调用分散两次:

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()

在此处输入图片说明

You don't have to predetermine the xaxis. 您不必预先确定xaxis。 It will adjust automatically to the data. 它将自动调整为数据。 If you dont want that you can of course set the limits or ticks manually. 如果您不希望这样做,当然可以手动设置限制或刻度。

You may then convert your strings to integers for plotting: 然后,您可以将字符串转换为整数以进行绘图:

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()

However, matplotlib is fine with plotting strings as long as they can be converted to a meaningful number or date. 但是,只要可以将字符串转换为有意义的数字或日期,matplotlib即可用于绘制字符串。 So the following works fine as well. 因此以下内容也可以正常工作。

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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM