简体   繁体   English

在x轴上绘制索引值并在y轴上绘制每个列值的频率的直方图

[英]Plot histogram with index values on x axis and frequencies of each column value on y axis

Based on the dataframe 基于数据框

import pandas as pd
df = pd.DataFrame({'cat1':[100,0,0,5],'cat2':[5,20,50,0]})
df 
    cat1    cat2
0   100 5
1   0   20
2   0   50
3   5   0

I want to plot a histogram such that the x axis represent the index values 0 to 3 and the bars for each index value show the distribution of the column values cat1 and cat2. 我想绘制一个直方图,以便x轴表示索引值0到3,每个索引值的条形图显示列值cat1和cat2的分布。

df.plot.hist(alpha=0.5)

plots the index values on the y and the category values on the x axis: 在y上绘制索引值,在x轴上绘制类别值:

在此处输入图片说明

And

df.transpose().plot.hist(alpha=0.5)

results in something I don't even fully understand: 结果导致我什至不完全了解:

在此处输入图片说明

What I actually want is a bar for each index value, that illustrates the values in the columns - eg for index 0, there should be a bar in cat1 color stretching to 100 on the y axis, containing another bar in cat2 color stretching to 5. 我真正想要的是每个索引值的条,以说明列中的值-例如,对于索引0,cat1颜色的条应在y轴上延伸到100,包含cat2颜色的另一条条应延伸到5 。

How can I achieve that? 我该如何实现?

you can use the pandas viz functions : 您可以使用pandas viz函数:

df.plot.bar(stacked=True) df.plot.bar(堆叠=真)

Try this, it's close that what you want: 试试这个,接近您想要的是:

import matplotlib.pyplot as plt

df.plot.barh()
plt.show()

Update thanks to SpghttCd: 感谢SpghttCd更新:

import matplotlib.pyplot as plt

df.plot.bar()
plt.show(

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

相关问题 如何为只有 1 列和多行的数据框创建直方图(行值应绘制在 x 轴上,列值应绘制在 y 轴上) - How to create a histogram for a dataframe with just 1 column and multiple rows (row values should be plot on x axis and column values on y axis) 如何绘制直方图,yaxis 为“对应于每个 x bin 的 y 值的总和”,x 轴为 python 中 x 的 n 个 bin? - How to plot a histogram with the yaxis as the "total of y values corresponding to each x bin" and x axis as n bins of x in python? 根据列的高度绘制带有x轴值的直方图 - Plot a histogram with the x axis values based on the height of the column 如何在pyplot中为每个x值在y轴上绘制平均值 - How to plot average in y axis for each x value in pyplot 直方图:X 轴和 Y 轴值显示不正确 - histogram : X-axis & Y-axis values not displaying correctly 如何在Python中从数据框绘制带有x和y轴的直方图 - How to plot histogram with x and y axis from dataframe in python 如何在Python中打印直方图的y轴值? - How to print y-axis values of histogram plot in Python? 如何在 Python 中更改直方图 Y 轴上的值 - How can I change the values on Y axis of Histogram plot in Python 使用索引作为 x 轴标签绘制直方图 - Plot a histogram using the index as x-axis labels 在python中构建一个直方图,一列作为x轴,3列作为y轴 - build a histogram in python with one column as x axis and 3 columns as y axes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM