【问题标题】:Plotnine bar plot order by variablePlotnine 条形图按变量顺序排列
【发布时间】:2017-12-05 20:35:05
【问题描述】:

我有一个关于订购条形图的问题。例如:

http://pythonplot.com/#bar-counts

(ggplot(mpg) +
aes(x='manufacturer') +
geom_bar(size=20) +
coord_flip() +
ggtitle('Number of Cars by Make')
)

如何按“mpg”排序?

【问题讨论】:

    标签: plotnine


    【解决方案1】:

    感谢 has2k1:https://github.com/has2k1/plotnine/issues/94

    如果 x 映射是一个有序的分类,它会被尊重。

    from plydata import *
    from plotnine import *
    from plotnine.data import mpg
    
    # count the manufacturer and sort by the count (see, plydata documentation
    # or find out how to do the same thing using raw pandas)
    m_categories = (
        mpg
        >> count('manufacturer', sort=True)
        >> pull('manufacturer')
    )
    
    df = mpg.copy()
    df['manufacturer'] = pd.Categorical(df['manufacturer'],     categories=m_categories, ordered=True)
    
    (ggplot(df) + 
       aes(x='manufacturer') +
    geom_bar(size=20) + 
    coord_flip() +
    ggtitle('Number of Cars by Make')
    )
    

    【讨论】:

      【解决方案2】:

      STHDA我发现:

      更改图例中项目的顺序 函数 scale_x_discrete 可用于将项目的顺序更改为“2”、“0.5”、“1”:

      p + scale_x_discrete(limits=c("D2", "D0.5", "D1"))
      

      我的目标是保持 df 的顺序,所以我做到了:

      scale_x_discrete(limits=df[xColumn].tolist())
      

      然后我意识到第一个栏项目在最后,所以我切换到:

      scale_x_discrete(limits=df[xColumn].tolist()[::-1])
      

      我无法使用reverse(),因为它可以正常工作并且不返回列表,所以limits 似乎没有看到效果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多