【问题标题】:python - making a multipanel bar chart with different categories for each panelpython - 为每个面板制作具有不同类别的多面板条形图
【发布时间】:2017-06-09 21:06:43
【问题描述】:

我想在 python 中制作多面板条形图,每个面板都有不同的类别。下面,我将展示一个示例,说明如何在 R 中使用 ggplot2 执行此操作。我正在寻找任何可以在 python 中执行等效操作的方法。到目前为止,我一直在 python-ggplot 和 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))

我可以在 python 中创建一个类似的数据框

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])
animalCounts = pd.DataFrame({'animal' : animal, 'attribute' : attribute, 'population': population})

在 python 中获得可比数字的任何帮助将不胜感激。如果我不必使用 rpy2,想象中的奖励积分。

【问题讨论】:

    标签: python r matplotlib ggplot2


    【解决方案1】:

    由于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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2023-02-22
      • 2017-03-28
      • 2019-08-15
      • 2014-06-28
      • 1970-01-01
      相关资源
      最近更新 更多