python为每个pan创建一个具有不同类别的多面板条形图

2024-10-02 04:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python制作多面板条形图,每个面板有不同的类别。下面,我将展示一个如何在R中使用ggplot2实现这一点的示例。我正在寻找任何可以实现等效的近似python。到目前为止,我一直在努力在pythonggplot和seaborn以及base matplotlib中做到这一点,但没有运气。在

你可以在我之前的一篇相关文章中看到这种尝试: using facet_wrap with categorical variables that differ between facet panes

在这篇文章中,我现在在问,是否有任何方法可以在python中创建我正在寻找的绘图(而不仅仅是尝试使用特定的方法)。在

好:R中的示例:

animal = c('sheep', 'sheep', 'cow', 'cow', 'horse', 'horse', 'horse')
attribute = c('standard', 'woolly', 'brown', 'spotted', 'red', 'brown', 'grey')
population = c(12, 2, 7, 3, 2, 4, 5)
animalCounts = data.frame(animal,attribute,population)

ggplot(aes(x = attribute, weight = population), data = animalCounts) + geom_bar() + 
facet_wrap(~animal, scales = "free") + scale_y_continuous ( limits= c(0,12))

barchart that I would like to make in python

我可以用python创建一个类似的数据帧

^{pr2}$

如果您能在python中获得可比的数据,我们将不胜感激。如果我不需要使用rpy2的话,我会得到假想的加分。在


Tags: 数据方法面板示例dataattributefacetpopulation
1条回答
网友
1楼 · 发布于 2024-10-02 04:37:43

由于last question中已经出现了这个问题,python ggplot不能使用facet_wrap。在

因此,可以选择使用标准pandas/matplotlib技术。在

import matplotlib.pyplot as plt
import pandas as pd

animal = pd.Series(['sheep', 'sheep', 'cow', 'cow', 'horse', 'horse', 'horse'], dtype = 'category')
attribute = pd.Series(['standard', 'woolly', 'brown', 'spotted', 'red', 'brown', 'grey'], dtype = 'category')
population = pd.Series([12, 2, 7, 3, 2, 4, 5])
df = pd.DataFrame({'animal' : animal, 'attribute' : attribute, 'population': population})

fig, axes = plt.subplots(ncols=3)
for i, (name, group) in enumerate(df.groupby("animal")):
    axes[i].set_title(name)
    group.plot(kind="bar", x = "attribute", y="population", ax=axes[i], legend=False)
    axes[i].set_ylabel("count")
    axes[i].set_xlabel("")

axes[1].set_xlabel("attribute")    
plt.tight_layout()
plt.show()

enter image description here

相关问题 更多 >

    热门问题