【问题标题】:Showing entire X Axis Ticks in Graph在图表中显示整个 X 轴刻度
【发布时间】:2016-06-12 12:43:27
【问题描述】:

我试图让我的图表的刻度标签完全显示,但我没有得到想要的结果,尽管我很努力。

如果我只使用autofmt_xdate(),日期会正确显示,但并非针对每个绘制的数据点;但是,如果我通过将 x 由 datetime 对象传递给 xtick() 来强制显示我的 x 刻度标签,它似乎只显示年份。

    fig1 = plt.figure(1)
    # x is a list of datetime objects
    plt.title('Portfolio Instruments')
    plt.subplot(111)
    plt.plot(x, y)
    plt.xticks(fontsize='small')
    plt.yticks([i * 5 for i in range(0, 15)])
    fig1.autofmt_xdate()
    plt.show()

将 x 传递给 plt.xticks() 的图形:

不将 x 传递给 plt.xticks() 的图表

我的错误在哪里?没找到。

问题 如何绘制 x 的所有数据点并将其格式化以显示我正在使用 autofmt_xdate() 传递图表的整个日期时间对象?

我有一个日期时间对象列表,我想将其作为绘图的 x 值传递。

【问题讨论】:

  • 如果您事先知道数据点的数量,或者如果始终存在相同数量的数据,您可以将 xticks 设置为等于某个数字。如果有一个更简单的例子给你同样的问题,那么给出更具体的答案会更容易。
  • 但这就是我已经在做的事情了,afaik,当我将列表x 传递给xticks() 时?我有已知数量的数据点。
  • 所以我认为autofmt_xdate 看到传递给xticks() 的日期时间对象并转换它们,就像以前一样。不是这种情况。唯一的区别是我强制图表在 x 轴上显示所有 x 刻度标签。
  • 我已经简化了上面的代码。
  • 在此处查看我的答案以获得另一种选择:stackoverflow.com/questions/39714724/… 我不确定在此处添加它是否可以。由于交叉发布。干杯

标签: python matplotlib


【解决方案1】:

将您想要标记的日期传递给xticks,然后使用plt.gca().xaxis.set_major_formatter 设置x 轴的主要格式化程序:

然后您可以使用DateFormatter from matplotlib.dates,并使用strftime 格式字符串来获取您问题中的格式:

import matplotlib.dates as dates
fig1 = plt.figure(1)
# x is a list of datetime objects
plt.title('Portfolio Instruments')
plt.subplot(111)
plt.plot(x, y)

plt.xticks(x,fontsize='small') 
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%b %d %Y'))

plt.yticks([i * 5 for i in range(0, 15)])

fig1.autofmt_xdate()
plt.show()

注意:我使用下面的代码为上面的图创建了数据,所以x 只是一个月中每个工作日(即没有周末)的datetime 对象列表。

import numpy as np
from datetime import datetime,timedelta

start = datetime(2016, 1, 1)
end = datetime(2016, 2, 1)
delta = timedelta(days=1)
d = start
weekend = set([5, 6])

x = []
while d <= end:
    if d.weekday() not in weekend:
        x.append(d)
    d += delta

y = np.random.rand(len(x))*70

【讨论】:

    【解决方案2】:

    我很确定我遇到了类似的问题,我解决它的方法是使用以下代码:

    def formatFig():
        date_formatter = DateFormatter('%H:%M:%S') #change the format here to whatever you like
        plt.gcf().autofmt_xdate()
        ax = plt.gca()
        ax.xaxis.set_major_formatter(date_formatter)
        max_xticks = 10      # sets the number of x ticks shown. Change this to number of data points you have
        xloc = plt.MaxNLocator(max_xticks)
        ax.xaxis.set_major_locator(xloc)
    
    def makeFig():
        plt.plot(xList,yList,color='blue')    
        formatFig()
    
    makeFig()
    plt.show(block=True)
    

    这是一个非常简单的示例,但您应该能够将formatfig() 部分转移到您的代码中使用。

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多