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

r - How do I manually change the key labels in a legend in ggplot2

I am preparing a plot for publication. I created a stacked box plot to show frequency of patients in each group who were some complicated accumulation of seronegatives versus not. The legend is using the labels from the data frame which are appropriate for us who are working on the project but no for publication. I want to change the names to something more rapidly understood by the reader.

So for instance run the following script

grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d"))
value <- runif(n=80, min=10, max=150)
outcome <- cut(value,2)
data <- data.frame(grp,value,outcome)
ggplot(data, aes(grp, fill=outcome)) + geom_bar() +xlab("group") 
             +ylab("number of subjects") + labs(fill="Serologic response")

That code creates key labels "(10.4,80]" and "(80,150]" which are not suitable for publication. Instead I would want "double negative" and "positive for a and/or b".

I guess I could go back to the dataframe and transform to get a new variable with the correct labeling. Or I could just relabel my factor? However, I would prefer to do it at the time of plotting.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The standard way is to use the scale functions to change the displayed labels for groups. You can replace your ggplot call with

ggplot(data, aes(grp, fill=outcome)) + geom_bar() +xlab("group") +
  ylab("number of subjects") + 
  scale_fill_discrete("Serologic response", 
                      breaks=c("(10.1,79.9]","(79.9,150]"), 
                      labels=c("double negative", "positive for a and/or b"))

Note that the scale's title has been incorporated into the scale_fill_discrete call. You can do this with the axes too, if you like

ggplot(data, aes(grp, fill=outcome)) + geom_bar() +
  scale_x_discrete("group") +
  scale_y_continuous("number of subjects") + 
  scale_fill_discrete("Serologic response", 
                      breaks=c("(10.1,79.9]","(79.9,150]"), 
                      labels=c("double negative", "positive for a and/or b"))

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

...