Python - 从 Pandas 数据创建单个水平堆积条形图? [英] Python - Create a single horizontal stacked bar chart from Pandas data?

查看:94
本文介绍了Python - 从 Pandas 数据创建单个水平堆积条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个单独的水平堆积条形图来替代饼图来显示百分比.

I'm looking to create a single horizontal stacked bar chart as an alternative to a pie chart to show percentages.

我很确定 plot.barh 会完成这项工作(它在我拥有的另一段代码中创建了多个堆叠条).但在这里它不会堆叠酒吧.我该如何解决?

I'm pretty sure plot.barh will do the job (it creates multiple stacked bars in another piece of code I have). But here it doesn't stack the bars. How do I fix it?

import pandas as pd
import matplotlib.pyplot as plt

data=pd.DataFrame(data={"R1":["Yes","Yes","Yes","No","No"]})
freq = data["R1"].value_counts(normalize=True)*100
fig,ax = plt.subplots()
freq.plot.barh(ax=ax,stacked=True)

推荐答案

堆叠意味着将多个系列的一个数据帧相互叠加,从而使它们的值累加.
您只有一个系列,有两个值,因此绘制在一个条形系列中.

Stacking means putting several series of one dataframe on top of each other, so their values cumulate.
You have a single series only, with two values, which consequently are plotted in one bar series.

您可以从系列中制作一个DataFrame,对其进行转换,以使 Yes No 是两列,每个列都有一个值,然后按照尝试的方式进行绘制:

You could make a DataFrame out of your series, transform it so that Yes and No are two columns with one value each and then plot it the way you tried:

freq.to_frame().T.plot.barh(stacked=True)

检查差异:

freq

# Yes    60.0
# No     40.0
# Name: R1, dtype: float64

freq.to_frame().T

#      Yes    No
# R1  60.0  40.0

这篇关于Python - 从 Pandas 数据创建单个水平堆积条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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