Python条形图和折线图在一个图中具有组 [英] Python bar and line chart with groups in one graph

查看:68
本文介绍了Python条形图和折线图在一个图中具有组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据:

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

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

I want to plot line and bar chart in one graph.
I tried to plot bar first, but it output two graphs (2 groups, G and I):

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

在那之后,我试图用它绘制折线图.

After that, I tried to draw line chart with it.

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轴上的所有标签.简而言之.它只是显示年份而不是年份和季度.
此外,该图也不在其上绘制条形图.

However, the plot is weird. It does not proper show all labels on x-axis. To be concise. it just show year rather than year and quarter.
Moreover, the plot does not plot bar chart on it either.

有什么建议吗?

我也尝试过:

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()

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

This plot is incorrect but can plot line and bar on same graph.

推荐答案

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

The problem is bar plot is sets the x-axis to range(len(dataset)), and use the corresponding labels, while line plot doesn't do so. So you can change the yq to string and use 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()

给予:

这篇关于Python条形图和折线图在一个图中具有组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆