控制ggplot2 geom_bar的填充顺序和组

时间:2020-12-16 15:02:43
library(ggplot2)


 data <- 
  data.frame(
    group=factor(c("a","c","b","b","c","a")),
    x=c("A","B","C", "D","E","F"),
    y=c(3,2,10,11,4,5)) 

> data
  group x  y
1     a A  3
2     c B  2
3     b C 10
4     b D 11
5     c E  4
6     a F  5

#And plot this:
ggplot(data)+
  geom_bar(aes(x=x, y=y, fill=group, order=group),
           stat="identity",
           position="dodge")+
  coord_flip()

This gives a figure where x is plotted according to factor levels: 控制ggplot2 geom_bar的填充顺序和组

这就给出了根据因子水平绘制x的图:

But how can one reorder x according to a custom order of the group variable and at the same time arrange within group according to say descending y. For instance if I want to plot first "c" (red), then "a" (green) and then "b" (blue) groups, the plot order of the x-axis (x variable) would be: E, B, F, A, D, C. Note this may have resemblance to this SO question.

但是一个重新排序x如何根据自定义的组内变量,同时安排组根据说下行y。例如,如果我想把第一个“c”(红色),然后“a”(绿色),然后“b”(蓝色)组,x轴(x变量)的情节顺序是:E、b,F,c,D,注意这可能与这样的问题。

1 个解决方案

#1


4  

You need first to format your dataframe without factor. Then you need to define the x column as factor but with order depending on y minimum per group. This specific ordering you want needs to be specified in levels argument.

您需要首先格式化您的dataframe而不是factor。然后需要将x列定义为因子,但顺序取决于每组y的最小值。需要在level参数中指定所需的特定排序。

Here we go:

我们开始吧:

data <- 
  data.frame(
    group=c("a","c","b","b","c","a"),
    x=c("A","B","C", "D","E","F"),
    y=c(3,2,10,11,4,5)) 

data$x = with(data, factor(x, levels=x[order(ave(y, group, FUN=min),y)]))

ggplot(data, aes(x, y, fill=group)) + 
  geom_bar(stat='identity', position='dodge') + 
  coord_flip()

控制ggplot2 geom_bar的填充顺序和组

#1


4  

You need first to format your dataframe without factor. Then you need to define the x column as factor but with order depending on y minimum per group. This specific ordering you want needs to be specified in levels argument.

您需要首先格式化您的dataframe而不是factor。然后需要将x列定义为因子,但顺序取决于每组y的最小值。需要在level参数中指定所需的特定排序。

Here we go:

我们开始吧:

data <- 
  data.frame(
    group=c("a","c","b","b","c","a"),
    x=c("A","B","C", "D","E","F"),
    y=c(3,2,10,11,4,5)) 

data$x = with(data, factor(x, levels=x[order(ave(y, group, FUN=min),y)]))

ggplot(data, aes(x, y, fill=group)) + 
  geom_bar(stat='identity', position='dodge') + 
  coord_flip()

控制ggplot2 geom_bar的填充顺序和组