我正在尝试从 pandas DataFrame 系列构建一个 pygal 条形图,并在其上应用 .value_counts()
例如无需将系列拆分为多列并单独添加这些列,如 documentation 中建议的那样和 this question .
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.
关于python - 从 Pandas 系列值计数创建 pygal.Bar 图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539714/