简体   繁体   English

如何在使用matplotlib的pyplot绘制的图形上设置x轴标签?

[英]How to set x-axis labels on a figure plotted using matplotlib's pyplot?

I'm trying to plot sales and expenses values (on y-axis) over years (on x-axis) as given below. 我正在尝试绘制以下年份(x轴)上的销售和费用值(y轴)。 I'm expecting that the following code will set 2004, 2005, 2006 and 2007 as x-axis values. 我期望以下代码将2004、2005、2006和2007设置为x轴值。 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. 让我知道如何在x轴上正确设置年份值。

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

在此处输入图片说明

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

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

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

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