【问题标题】:X-axis tick labels are too dense when drawing plots with matplotlib使用 matplotlib 绘制绘图时 X 轴刻度标签太密集
【发布时间】:2019-02-20 09:42:10
【问题描述】:

我正在绘制 matplotlib 图,我的 x 轴由 YYYYMM 格式的年份和月份字符串组成,例如 2019 年 1 月的 201901。

我的问题是一些数据跨越了很长一段时间,这使得 x 轴刻度标签如此密集,以至于它们相互堆积,变得不可读。

我尝试缩小字体并将标签旋转 90 度,这很有帮助,但对于我的某些数据来说仍然不够。

这是我的 x 轴之一的示例,看起来不错:

这里是一个 x 轴的例子,因为数据跨越了很长一段时间:

所以我希望 matplotlib 在刻度标签开始相互堆积时跳过打印一些刻度标签。例如,打印一月的标签,跳过打印二月,三月,四月和五月的标签,打印六月的标签,跳过打印七月,八月的标签等。但我不知道该怎么做?

或者我可以使用任何其他类型的解决方案来解决这个问题吗?

【问题讨论】:

  • 绘制datetime 对象而不是字符串。然后整个问题就消失了。
  • 字符串被视为等间距的“类别”。如果您将“boo”放在那里,它将被视为与您的其他字符串相同。正如@ImportanceOfBeingErnest 所说,最好将其转换为日期时间,以便将 x 值视为数字。
  • 感谢您的反馈 ImportanceOfBeingErnest,Jody。

标签: python matplotlib


【解决方案1】:

一个快速的肮脏解决方案如下:

ax.set_xticks(ax.get_xticks()[::2])

这只会显示每秒 xtick。如果您只想显示每个第 n 个刻度,您可以使用

ax.set_xticks(ax.get_xticks()[::n])

如果您没有ax 的句柄,您可以使用ax = plt.gca() 获取一个句柄。

或者,您可以指定要使用的 xticks 数量:

plt.locator_params(axis='x', nbins=10)

【讨论】:

    【解决方案2】:

    另一种解决方案可能如下:

    x = df['Date']
    y = df['Value']
    
    # Risize the figure (optional)    
    plt.figure(figsize=(20,5))
        
    # Plot the x and y values on the graph
    plt.plot(x, y)
        
    # Here you specify the ticks you want to display
    # You can also specify rotation for the tick labels in degrees or with keywords.
    plt.xticks(x[::5],  rotation='vertical')
    
    # Add margins (padding) so that markers don't get clipped by the axes
    plt.margins(0.2)
    
    # Display the graph
    plt.show()
    

    【讨论】:

    • 上面代码的excel文件在哪里看的?
    • @just_learning... 在 df 中读取 excel 文件。使用 df = pandas.read_excel("pathToExcelFile")
    • 加投票支持轮换 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多