我在Python中使用Rpy2有一个R dataframe对象,如下所示:

cat name num
1   a  bob   1
2   b  bob   2
3   a mary   3
4   b mary   4


我想将其绘制为具有翻转坐标的geom_bar,并且使条形的顺序与图例的顺序匹配(不更改图例)。在这里和其他邮件列表中已经有人问过这个问题,但是我对如何将R订购代码转换为rpy2感到困惑。这是我当前的代码:

# attempting to reorder bars so that value 'a' of cat is first (in red)
# and value 'b' of cat is second (in green)
labels = tuple(["a", "b"])
labels = robj.StrVector(labels)
variable_i = r_df.names.index("cat")
r_df[variable_i] = robj.FactorVector(r_df[variable_i],
                                     levels=labels)
r.pdf("test.pdf"))
p = ggplot2.ggplot(r_df) + \
    ggplot2.geom_bar(aes_string(x="name",
                                y="num",
                                fill="cat"),
                     position=ggplot2.position_dodge(width=0.5)) + \
    ggplot2.coord_flip()
p.plot()


这样就可以得到具有正确图例的图形(“ a”为红色的第一位,“ b”为绿色的第二位),但是对于每个“”值,条形都以绿色/红色(“ b”,“ a”)的顺序显示名称'。我对上一个的印象帖子是因为coord_flip()翻转订单。如何更改条形顺序(不是图例顺序)以匹配当前图例,在每个闪避的条形组中首先绘制红色条形?谢谢。

编辑:*

在rpy2中尝试了@joran的解决方案:

labels = tuple(["a", "b"])
labels = robj.StrVector(labels[::-1])
variable_i = r_df.names.index("cat")
r_df[variable_i] = robj.FactorVector(r_df[variable_i],
                                     levels=labels)
p = ggplot2.ggplot(r_df) + \
    ggplot2.geom_bar(aes_string(x="name",
                                y="num",
                                fill="cat"),
                     stat="identity",
                     position=ggplot2.position_dodge()) + \
    ggplot2.scale_fill_manual(values = np.array(['blue','red'])) + \
    ggplot2.guides(fill=ggplot2.guide_legend(reverse=True)) + \
    ggplot2.coord_flip()
p.plot()


这是行不通的,因为未找到ggplot2.guides,但这仅用于设置图例。我的问题是:为什么scale_fill_manual是必需的?我不想指定我自己的颜色,我想要默认的ggplot2颜色,但我只想将排序设置为特定的方式。有道理,对于coord_flip,我需要反向排序,但这还不足以独立于图例而对条形进行明显排序(请参见我的labels[::-1])。对此有何想法?

最佳答案

抱歉,我的机器上没有rpy设置,但是我可以通过此R / ggplot2代码获得我认为您正在描述的内容:

dat$cat <- factor(dat$cat,levels = c('b','a'))

ggplot(dat,aes(x = name,y = num, fill = cat)) +
    geom_bar(stat = "identity",position = "dodge") +
    coord_flip() +
    scale_fill_manual(values = c('blue','red')) +
    guides(fill = guide_legend(reverse = TRUE))




基本上,我只是反转因子水平,并反转图例顺序。令人费解,但看起来像您所描述的。 (此外,您确实想要stat = "identity",对吗?)

关于python - 在Python中使用Rpy2对具有翻转坐标的ggplot2条进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17644471/

10-12 17:54
查看更多