【问题标题】:Python bar and line chart with groups in one graphPython 条形图和折线图,在一个图中包含组
【发布时间】:2019-10-16 11:00:09
【问题描述】:

我有这样的数据:

Group   yq        Value1    Value2
G       2014Q1     0.07        1.1
G       2014Q2     0.06        1.09
G       2014Q3     0.09        1.11
G       2014Q4     0.04        1.13
I       2014Q1     0.10        1.2
I       2014Q2     0.13        1.25
I       2014Q3     0.15        1.23
I       2014Q4     0.18        1.4

我想在一张图中绘制折线图和条形图。
我尝试先绘制条形图,但它输出了两个图形(2 组,G 和 I):

import matplotlib.pyplot as plt
ax = dataset.groupby('Group')[['yq', 'Value1']].plot(x = 'yq', kind='bar')

之后,我尝试用它绘制折线图。

fig, ax1 = plt.subplots(figsize=(7, 5))
ax2 = ax1.twinx()
dataset[['Value1', 'yq', 'Group']].groupby('Group').plot(x = 'yq', kind='bar', color='y', ax=ax1)
dataset[['Value2', 'yq', 'Group']].groupby('Group').plot(x = 'yq', kind='line', marker='d', ax=ax2)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()

然而,情节很奇怪。它不能正确显示 x 轴上的所有标签。简明扼要。它只显示年份而不是年份和季度。
此外,该图也没有在其上绘制条形图。

有什么建议吗?

我也试过了:

fig, ax = plt.subplots(figsize=(10, 5))
dataset[['Value1', 'yq', 'Group']].plot(x = 'yq', kind='bar', stacked=False, title='get_title', color='grey', ax=ax, grid=False)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), dataset[['Value2']].values, linestyle='-', marker='o', color='k', linewidth=1.0, label='percentage')
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='best')
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
fig.autofmt_xdate()
plt.show()

此图不正确,但可以在同一张图上绘制线条和条形图。

【问题讨论】:

  • 您的代码对我有用。我将年份和季度作为 x 轴标签。
  • 对我来说很好。确保yq 不是datetime 类型。这将使条形图和线图网格化。
  • type(dataset.yq); pandas.core.series.Series
  • 试试dataset.yq.dtype
  • 数据集中缺少一个[['Value2', 'yq', 'Group']]

标签: python pandas matplotlib group-by seaborn


【解决方案1】:

问题是bar plot 将x 轴设置为range(len(dataset)),并使用相应的标签,而line plot 没有这样做。因此,您可以将yq 更改为字符串并使用 seaborn:

dataset.yq = dataset.yq.astype(str)

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax1)
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', marker='d', ax=ax2)
plt.show()

给予:

【讨论】:

  • 太棒了!是否可以将 x 轴的标签设置为垂直或 45 角,并将条形图 y 轴设置为百分比并显示在每个条上?
  • seaborn 太棒了。但是为什么matplotlib 不能完成这个呢?
  • 百分比标签可以使用:ax1.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax1.get_yticks()])。注释条形图很棘手,您可以搜索此站点以获取解决方案。 matplotlib 可以,但需要大量调整,这就是 seaborn 所做的,因为(我认为)seaborn 只是 matplotlib 的包装器。
  • 还有可能因为x轴的标签有点拥挤,所以可以把它做成垂直的吗
  • ax1.set_xticklabels(ax1.get_xticks(), rotation=90)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
相关资源
最近更新 更多