使用Rpy2翻转坐标订购GGPLOT2吧我有在Python的R数据框对象,使用Rpy2,看起来像这样:可以用Python
cat name num
1 a bob 1
2 b bob 2
3 a mary 3
4 b mary 4
我想绘制它与翻转COORDS一个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')为'name'的每个值。来自prev的我的印象。帖子是,这是因为coord_flip()
翻转订单。如何更改酒吧订单(不是图例顺序)以匹配当前图例,在每个躲闪条形组中首先绘制红色条形图?谢谢。
编辑:*
试图@ joran在rpy2解决方案:
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]
)。对此有何想法?
ggplot2的'guides'没有被模块'rpy2.robjects.lib.ggplot2'自定义映射('guides'是比较近的,我错过了它的介绍,没有人抱怨到现在为止)。与此同时,试着用'ggplot2.ggplot2.guides()'修改你的代码。 – lgautier