Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - reorder dodge bar plots (ggplot2)

I have a data frame lot_main that looks like this:enter image description here

I want to make a bar plot with columns reorders according to the wordcount.

library(ggplot2)
library(viridis)
lotr_main %>% ggplot(aes(x = Character, y = wordcount, fill = Film)) + 
geom_bar(stat="identity",position = "dodge") +
coord_flip() +
scale_fill_viridis("Film",discrete = TRUE, option = "C")

The plot I got: enter image description here

What I want is for each character, the bars are reorders with the longest on the top and shortest at the bottom. The orders of the bars don't need to be the same for each character.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You essentially want to fill by one thing, and order by another. A solution is thus to pry them apart and create a separate 'order' variable. Of note, I don't know if sorting your bars by value instead of having the same sequence each 'group' makes your plot more understandable.....

create some data:

library(data.table)


set.seed(123)
dat <- expand.grid(group=LETTERS[1:3],
                   subgroup=LETTERS[1:3])
dat$value <- runif(nrow(dat))
setDT(dat)

Create the order variable:

dat[,order:=order(value),by=group]

Create the plot

p1 <- ggplot(dat, aes(x=group,y=value, fill=subgroup,group=order))+
  geom_bar(aes(group=order),position="dodge", stat="identity") +
  coord_flip()
p1

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...