1

我在 Python 中有一个使用 Rpy2 的 R 数据框对象,如下所示:

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]独立于图例重新排序条形(请参阅我的)。对此有何想法?

4

1 回答 1

2

很抱歉,我的机器上没有 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",对吧?)

于 2013-07-15T02:03:40.093 回答