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
563 views
in Technique[技术] by (71.8m points)

plot - R: Reorder facet_wrapped x-axis with free_x in ggplot2

I'm trying to use reorder in a facet-wrapped plot that also uses scales = free_x in ggplot2, but the reorder function isn't reordering the x-axis properly. Here's what I'm running:

library(ggplot2)

df <- read.table("speaking_distribution_by_play.txt",
                 header = F,
                 sep = "")

ggplot(df, aes(x=reorder(V2, V3), y=V3)) + 
  geom_bar(stat = "identity") +
  facet_wrap(~V1, ncol = 4, scales = "free_x") + 
  opts(title = "Distribution of Speakers in Shakespearean Drama") + 
  xlab("Speaking Role") + 
  ylab("Words Spoken") +
  opts(axis.text.x=theme_text(angle=90, hjust=1))

Running that code on the data frame read from this tab-separated file yields a plot in which the x-axis of each faceted plot is only partially ordered. Someone else on SO asked a very similar question, but the only proposed solution was to use grid arrange. Because my data set is quite a bit larger than the data set in that question, though, this won't be a terribly swift operation, so I wanted to ask: Is there a way to reorder the x axis of each faceted plot so as to show the bars in increasing (or decreasing) order of size? I would be very grateful for any help others can offer on this question.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

With a slightly different approach, you can keep the labels in the area under the charts. This version creates unique x breaks by concatenating V1 and V2 in a way similar to jlhoward's method but then restores V2 as the x labels using the function roles in the code below in the scale_x_discrete statement.

library(ggplot2)
df <- read.table("speaking_distribution_by_play.txt",
             header = F,
             sep = "")

# Creates a small test subset; remove for complete set 
df <- df[df$V1 %in% c("Mac.xml","MM.xml","MND.xml","MV.xml"),]

# used to create x-axis label restoring original name of role
roles <- function(x) sub("[^_]*_","",x )   

ggplot(cbind(df, V4=paste(df$V1,df$V2,sep="_")), aes(x=reorder(V4,V3), y=V3) ) + 
geom_bar(stat = "identity") +
facet_wrap(~ V1,  ncol=4, scales = "free_x") +
labs(title = "Distribution of Speakers in Shakespearean Drama") + 
xlab("Speaking Role") + 
ylab("Words Spoken") +
scale_x_discrete(labels=roles) +
theme(axis.text.x=element_text(angle=90, hjust=1)) 

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

1.4m articles

1.4m replys

5 comments

57.0k users

...