从 Pandas 系列值计数创建 pygal.Bar 图表?

Creating pygal.Bar chart from Pandas series value counts?

我正在尝试从应用了 .value_counts() 的 pandas DataFrame 系列构建一个 pygal 条形图,例如无需按照 documentation and .

中的建议将系列拆分为多列并单独添加这些列
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

理想情况下,结果看起来像 this question 的解决方案中的情节。这能做到吗?

提前致谢!

我认为这就是您的目标:

Pygal 不能直接绘制 Pandas 对象,但您可以利用 value_counts 返回的 Series 对象的属性来设置 x图表的标签并将计数添加为一系列数据。

上面的图表是使用以下代码创建的:

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.