简体   繁体   English

Python-从Pandas数据创建单个水平堆积条形图?

[英]Python - Create a single horizontal stacked bar chart from Pandas data?

I'm looking to create a single horizontal stacked bar chart as an alternative to a pie chart to show percentages. 我希望创建一个水平堆积条形图,以替代饼图以显示百分比。

I'm pretty sure plot.barh will do the job (it creates multiple stacked bars in another piece of code I have). 我非常确定plot.barh会完成这项工作(它在我拥有的另一段代码中创建了多个堆叠的条形图)。 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. 您只有一个序列,带有两个值,因此以一个条形图进行绘制。

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: 您可以从系列中制作一个DataFrame,对其进行转换,使YesNo是两列,每列一个值,然后按照尝试的方式绘制它:

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

在此处输入图片说明


to examine the difference: 检查差异:

freq

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

freq.to_frame().T

#      Yes    No
# R1  60.0  40.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM