简体   繁体   中英

How to put labels of legend inside plot in ggplot2

Context: R/ggplot2.

Is there an automated way (or even a manual way) to put the legend factors inside the plot like the energies here (Co, 4,6,10,...), instead of having them in a regular legend box next to the plot ?

资料来源:放射肿瘤学物理学:教师和学生手册,EB。 Podgorsak

Source: Radiation Oncology Physics: A Handbook for Teachers and Students, EB. Podgorsak

So this seems close. I'd characterize this as "semi-automatic": there's definitely some tweaking needed, but most of the work is done for you...

The tricky bit is not placing the text labels ( geom_text(...) ), but creating the breaks in the plotted curves. This is done with geom_rect(...) , where the width of the rectangles are set to the maximum label width, as determined using strwidth(...) .

# create sample data
df <- data.frame(x=rep(seq(0,20,.01),5),k=rep(1:5,each=2001))
df$y <- with(df,x*exp(-x/k))

library(ggplot2)
eps.x <- max(strwidth(df$k))  # maximum width of legend label
eps.y <- eps.x*diff(range(df$y))/diff(range(df$x))
ggplot(df,aes(x,y))+
  geom_line(aes(group=factor(k)))+
  geom_rect(data=df[df$x==5,],
            aes(xmax=x+eps.x, xmin=x-eps.x, ymax=y+eps.y, ymin=y-eps.y),
            fill="white", colour=NA)+
  geom_text(data=df[df$x==5,],aes(x,y,label=k))+
  theme_bw()

If you want to color the lines too:

ggplot(df,aes(x,y))+
  geom_line(aes(color=factor(k)))+
  geom_rect(data=df[df$x==5,],
            aes(xmax=x+eps.x, xmin=x-eps.x, ymax=y+eps.y, ymin=y-eps.y),
            fill="white", colour=NA)+
  geom_text(data=df[df$x==5,],aes(x,y,label=k), colour="black")+
  scale_color_discrete(guide="none")+
  theme_bw()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM