【发布时间】: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