简体   繁体   English

R ggplot水平闪避条形图顺序

[英]R ggplot horizontal dodged barplot order

I would like to create a simple horizontal barplot with dodged bars, but I am struggeling with the ordering of the (horizontal) bars. 我想创建一个简单的带有条形图的水平条形图,但是我在(水平)条形图的排序中苦苦挣扎。 When I do a normal barplot (stacked or dodged) I can easily control the order of the bars by setting useful factor levels and ordering the data frame according to the corresponding variable. 当我进行普通条形图(堆积或躲避)时,可以通过设置有用的因子水平并根据相应变量对数据框进行排序来轻松控制条形图的顺序。 However, ordering the data frame does not seem to have any effect on the order of the bars in the horizontal plot. 但是,对数据框进行排序似乎对水平图中的条形顺序没有任何影响。 I found some similar questions, but I am not sure whether they correspond to my problem (the plots look a bit different). 我发现了一些类似的问题,但是我不确定它们是否与我的问题相对应(情节看起来有些不同)。

df1 <- data.frame (year = as.factor(c(rep(2015,3),rep(2016,3),rep(2017,3))),
value = c(50,30,20,60,70,40,20,50,80),
set = rep(c("A","B","C"),3) )

ggplot() + geom_bar(data= df1, aes(y=value, x=set, fill=year), 
stat="identity", position="dodge" ) +
coord_flip()

What I want is a horizontal plot that shows the 2015-bar on top and the 2017-bar on the bottom. 我想要的是一个水平图,顶部显示2015年柱形图,底部显示2017年柱形图。 Interestingly, the bars are ordered that way when I leave out coord_flip(), but I need the plot to be horizontal. 有趣的是,当我省略coord_flip()时,条形图的排序方式如此,但我需要使图线水平。 Ordering the data this way does not change the plot: 以这种方式对数据进行排序不会更改绘图:

df1 <- df1[rev(order(df1$year)),]

I am grateful for any hint :) 我很感谢任何提示:)

You've hit on one of ggplot2's idiosyncrasies - the ordering of bars after coord_flip gets a little unintuitive. 您碰到了ggplot2的一种特质-coord_flip之后的coord_flip顺序有点不直观。 To change it, you have to reverse the order of your factor levels in df1$year , not just the values themselves. 要更改它,您必须颠倒df1$year因子水平的顺序,而不仅仅是值本身。 See below: 见下文:

library(ggplot2)

df1 <- data.frame (year = as.factor(c(rep(2015,3),rep(2016,3),rep(2017,3))),
                   value = c(50,30,20,60,70,40,20,50,80),
                   set = rep(c("A","B","C"),3) )

levels(df1$year)
#> [1] "2015" "2016" "2017"

df1$year <- factor(df1$year, levels = rev(levels(df1$year)))

ggplot(df1) +
  geom_bar(aes(y=value, x=set, fill=year), 
           stat="identity", position="dodge" ) +
  coord_flip()

If you want to keep your legend in the original order, you can access this with guide_legend . 如果您想使图例保持原始顺序,则可以使用guide_legend进行访问。

ggplot(df1) +
  geom_bar(aes(y=value, x=set, fill=year), 
           stat="identity", position="dodge" ) +
  guides(fill = guide_legend(reverse = TRUE)) +
  coord_flip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM