简体   繁体   English

从熊猫系列价值计数创建pygal.Bar图表?

[英]Creating pygal.Bar chart from Pandas series value counts?

I'm trying to build a pygal bar chart from a pandas DataFrame series onto which .value_counts() is applied eg without having to split the series into multiple columns and add those columns individually, as suggested in the documentation and this question . 我正在尝试从应用了.value_counts()的pandas DataFrame系列构建一个pygal条形图,例如,不必按照文档此问题中的建议将系列拆分成多个列并单独添加这些列。

import pandas as pd
import pygal

df = pd.DataFrame.from_dict({'categorical': ['foo','foo','bar','foo','bar','too']})

series = df.categorical.value_counts()
series
> foo    3
  bar    2
  too    1

Ideally the result looks like the plot in the solution to this question . 理想情况下,结果看起来像是该问题解决方案中的情节。 Can this be done? 能做到吗?

Thanks in advance! 提前致谢!

I think that this is what you were aiming for: 我认为这就是您的目标:

从熊猫系列创建的Pygal条形图

Pygal doesn't isn't able to plot Pandas objects directly, but you can take advantage of the attributes of the Series object returned by value_counts to set the x labels of a chart and add the counts as a series of data. Pygal不能直接绘制Pandas对象,但是您可以利用value_counts返回的Series对象的属性来设置图表的x标签,并将计数添加为一系列数据。

The chart above was created with this code: 上面的图表是使用以下代码创建的:

import pandas as pd
import pygal

df = pd.DataFrame.from_dict({'categorical': ['foo','foo','bar','foo','bar','too']})
series = df.categorical.value_counts()

chart = pygal.Bar(width=400, height=300)
chart.x_labels = series.index
chart.add("Count", series.values)

chart.render_to_png("bar.png")  # Or any other output option.

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

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