简体   繁体   中英

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:

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? The xaxis is predetermined.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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