Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

r - Control the fill order and groups for a ggplot2 geom_bar

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: enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...