【问题标题】:Fix overlapping of X-axis values on Matplotlib graph修复 Matplotlib 图上 X 轴值的重叠
【发布时间】:2020-10-14 16:11:03
【问题描述】:

我的 Matplotlib 图表需要一些帮助。项目可以查看here(目前在new-graph分支下工作)。

作为这个项目所做的总结:

  • 下载两个 CSV 文件(英国 COVID-19 病例和英国 COVID-19 死亡病例)
  • 将 CSV 文件解析为 Pandas 数据框,以仅包含包含日期和累积值的列
  • 使用 Matplotlib 条形图将这两组数据绘制在一张图上

我的问题是 Matplotlib 不会自动分隔 X 轴值(日期)。我不确定是不是因为 Matplotlib 没有将它们识别为日期或我犯的其他错误。 Here is what the graph currently looks like.

编辑: 抱歉,我忘了将代码添加到问题中。在这里……

import matplotlib.pyplot as plt

def plot(cases,deaths):
    #cases.plot(x='Specimen date',y='Cumulative lab-confirmed cases',color='green')
    #deaths.plot(x='Reporting date',y='Cumulative deaths',color='red')
    plt.figure("Cumulative deaths and cases")
    ax = plt.gca()
    cases.plot(kind='bar', x='Specimen date', y='Cumulative lab-confirmed cases',ax=ax, color='green')
    deaths.plot(kind='bar', x='Reporting date', y='Cumulative deaths', ax=ax, color='red')
    plt.show()

【问题讨论】:

  • 请在问题正文中包含您的代码,以便人们更容易地帮助您。
  • 完全忘记了这一点。我已经修好了,对不起!

标签: python pandas matplotlib graph statistics


【解决方案1】:

问题在于,对于绘图的大小而言,刻度标签太多了。

我建议间隔刻度,使其适合您的情节。这可以使用来自Axis.axisset_xticks 来完成。例如,在下面的示例中,我每 5 次出现一个刻度。

为了进一步提高可读性,我还在刻度标签上添加了 45 度的旋转。注意那里的参数ha="right"。它用于确保标签的右侧部分与刻度线对齐。

def plot(cases, deaths):
    plt.figure("Cumulative deaths and cases")
    ax = plt.gca()
    cases.plot(kind='bar', x='Specimen date', y='Cumulative lab-confirmed cases', ax=ax, color='green')
    deaths.plot(kind='bar', x='Reporting date', y='Cumulative deaths', ax=ax, color='red')
   
    ax.xaxis.set_ticks(range(0, len(cases), 5))
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right")

    plt.show()

【讨论】:

    【解决方案2】:

    您可能希望使用此函数使 xticks 更小: plt.xticks(fontsize=desired_size)

    【讨论】:

    • 您好,感谢您的回复。如果我增加窗口的大小,这似乎是一个很好的解决方法。有没有办法让它们分开?例如。 21/03/2020 ... 23/03/2020 ... (而不是它们都在轴上?)
    • @SpiritedByte 您可以使用plt.xticks() 函数中的参数rotation 来使刻度水平,如果这是你想要的。如果您希望刻度出现在多行上,也许这篇文章很有用link
    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2015-11-18
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多