条形图比较两列

时间:2019-04-10 16:44:41

标签: python pandas bar-chart seaborn

我想画一个条形图,比较每个时间轴(12个月的发票)上两个收入变量的变化。

我想使用sns.barplot,但是不能使用“ hue”(因为2个变量不是子类别?)。还有另一种方法,就像使用色相一样简单吗?我可以“创建”色调吗?

这是我的数据的一小部分样本:

(我确实将表格转换为数据透视表)

[In]

data_pivot['Revenue-Small-Seller-in'] = data_pivot["Small-Seller"] + data_pivot["Best-Seller"] + data_pivot["Medium-Seller"]
data_pivot['Revenue-Not-Small-Seller-in'] = data_pivot["Best-Seller"] + data_pivot["Medium-Seller"]
data_pivot

[Out]

InvoiceNo   Month   Year    Revenue-Small-Seller-in Revenue-Not-Small-Seller-in
 536365       12    2010             139.12                   139.12
 536366       12    2010              22.20                    11.10
 536367       12    2010             278.73                   246.93

sorry for the ugly presentation of my data, see the picture to see the complete table (as there are multiple columns))

1 个答案:

答案 0 :(得分:0)

您可以这样做:

render_df = data_pivot[data_pivot.columns[-2:]]
fig, ax = plt.subplots(1,1)
render_df.plot(kind='bar', ax=ax)
ax.legend()
plt.show()

输出:

enter image description here

或者像您要求的sns样式

render_df = data_pivot[data_pivot.columns[-2:]].stack().reset_index()
sns.barplot('level_0', 0, hue='level_1',
            render_df)

render_df之后的stack()是:

+---+---------+-----------------------------+--------+
|   | level_0 |           level_1           |   0    |
+---+---------+-----------------------------+--------+
| 0 |       0 | Revenue-Small-Seller-in     | 139.12 |
| 1 |       0 | Revenue-Not-Small-Seller-in | 139.12 |
| 2 |       1 | Revenue-Small-Seller-in     | 22.20  |
| 3 |       1 | Revenue-Not-Small-Seller-in | 11.10  |
| 4 |       2 | Revenue-Small-Seller-in     | 278.73 |
| 5 |       2 | Revenue-Not-Small-Seller-in | 246.93 |
+---+---------+-----------------------------+--------+

并输出:

enter image description here