Reputation: 193
I'm trying to plot sales and expenses values (on y-axis) over years (on x-axis) as given below. I'm expecting that the following code will set 2004, 2005, 2006 and 2007 as x-axis values. But, it is not showing as expected. See the image attached below. Let me know how to set the years values correctly on x-axis.
import matplotlib.pyplot as plt
years = [2004, 2005, 2006, 2007]
sales = [1000, 1170, 660, 1030]
expenses = [400, 460, 1120, 540]
plt.plot(years, sales)
plt.plot(years, expenses)
plt.show()
Upvotes: 2
Views: 3044
Reputation: 28848
This would also do the work, in a different way:
fig=plt.figure()
ax = fig.add_subplot(111)
years = [2004, 2005, 2006, 2007]
sales = [1000, 1170, 660, 1030]
ax.plot(years, sales)
ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%d'))
plt.show()
Upvotes: 4
Reputation: 3070
The following piece of code should work for you
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
years = [2004, 2005, 2006, 2007]
sales = [1000, 1170, 660, 1030]
expenses = [400, 460, 1120, 540]
x = [dt.datetime.strptime(str(d),'%Y').date() for d in years]
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
plt.plot(x, sales)
plt.plot(x, expenses)
plt.gcf().autofmt_xdate()
plt.show()
Upvotes: 1