【问题标题】:How to set x-axis labels on a figure plotted using matplotlib's pyplot?如何在使用 matplotlib 的 pyplot 绘制的图形上设置 x 轴标签?
【发布时间】:2013-07-29 08:33:41
【问题描述】:

我正在尝试绘制多年来(在 x 轴上)的销售和费用值(在 y 轴上),如下所示。我期望以下代码将 2004、2005、2006 和 2007 设置为 x 轴值。但是,它没有按预期显示。请参阅下面的图片。让我知道如何在 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()

【问题讨论】:

  • 为了将来参考,这称为 offset,并且可以在使用 ScalarFormatter 时通过调用 ax.xaxis.get_major_formatter().set_useOffset(False) 来禁用,就像在这种情况下一样。跨度>

标签: python matplotlib


【解决方案1】:

这也会以不同的方式完成工作:

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

【讨论】:

    【解决方案2】:

    下面的代码应该适合你

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多