【问题标题】:Matplotlib python Bar Plot: how to show months only rather than showing dates for bar plot in matplotlib?Matplotlib python Bar Plot:如何仅显示月份而不是在matplotlib中显示条形图的日期?
【发布时间】:2021-05-25 18:56:51
【问题描述】:

我有一个包含日期、站点 ID 和降雨量 mm/天的数据框。我正在尝试生成条形图。我正在使用 matplotlib 子图来生成条形图。一旦我运行下面的代码,它会生成一个条形图(如下所示),x 轴上有混乱的日期。我正在分析 2017-04-16 到 2017-08-16 的数据。我想显示 2017 年 4 月、2017 年 5 月等月份。谁能帮帮我吗?提前致谢。

fig = plt.figure(dpi= 136, figsize=(16,8))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
df1[216].plot(ax = ax1, kind='bar', stacked=True)
df1[2947].plot(ax = ax2, kind='bar')
df1[5468].plot(ax = ax3, kind='bar')
df1[1300].plot(ax = ax4, kind='bar')
plt.show()

这是我得到的输出

这是我拥有的数据框

【问题讨论】:

标签: python pandas matplotlib plot bar-chart


【解决方案1】:

pandas 中的条形图旨在比较类别,而不是显示时间序列或其他类型的连续变量,如 docstring 所述:

条形图显示离散类别之间的比较。一个轴 该图显示了正在比较的特定类别,而另一个 轴表示测量值。

这就是为什么 pandas 条形图的 x 轴刻度由从零开始的整数组成,并且默认情况下每个条形都有一个刻度和刻度标签,而不管 x 变量的数据类型如何。

您有两个选择:使用plt.bar 绘制数据并使用matplotlib.dates module 中的日期刻度定位器和格式化程序,或者坚持使用pandas 并根据日期时间索引应用自定义刻度和刻度标签,并使用适当的@ 格式化987654323@ 就像这个例子:

import numpy as np               # v 1.19.2
import pandas as pd              # v 1.2.3
import matplotlib.pyplot as plt  # v 3.3.4

# Create sample dataset
rng = np.random.default_rng(seed=1234)
date = pd.date_range('2017-04-16', '2017-06-16', freq='D')
df = pd.DataFrame(rng.exponential(scale=7, size=(date.size, 4)), index=date,
                  columns=['216','2947','5468','1300'])

# Generate plots
axs = df.plot.bar(subplots=True, layout=(2,2), figsize=(10,7),
                  sharex=False, legend=False, color='tab:blue')

# Create lists of ticks and tick labels
ticks = [idx for idx, timestamp in enumerate(df.index)
         if (timestamp.month != df.index[idx-1].month) | (idx == 0)]
labels = [tick.strftime('%d-%b\n%Y') if (df.index[ticks[idx]].year
          != df.index[ticks[idx-1]].year) | (idx == 0) else tick.strftime('%d-%b')
          for idx, tick in enumerate(df.index[ticks])]

# Set ticks and tick labels for each plot, edit titles
for ax in axs.flat:
    ax.set_title('Station '+ax.get_title())
    ax.set_xticks(ticks)
    ax.set_xticklabels(labels, rotation=0, ha='center')

ax.figure.subplots_adjust(hspace=0.4)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-25
    • 2021-12-22
    • 2015-05-21
    • 2017-11-24
    • 1970-01-01
    • 2018-11-19
    • 2020-02-05
    • 2015-10-11
    相关资源
    最近更新 更多