如何在facet_wrap中正确使用贴标机

时间:2016-07-07 20:28:38

标签: r ggplot2

我有下面的情节,我希望facet情节标签是" lbl" =

> lbl
[1] "0% - 10%"  "10% - 20%"

如何将labeller添加到facet_wrap以显示该文本以及labeller如何正确处理从labeller函数输出的顺序?即如果我有20个图,贴标签器如何正确地按正确的顺序标记图?谢谢。

这是代码:

x = c( rep(c(1,2,3,4,5),4)  )
group = c( rep(c(10,10,10,10,10),2),rep(c(20,20,20,20,20),2) )
lbl = paste0(  c("0%", paste0(   unique(group)[1:(length(unique(group))-1)]   ,"%" )  ) 
               ," - ",
               paste0(unique(group),"%"))
lbl
value = rnorm(20)
dat = data.frame( x= x , group  = group, value = value)
dat = dat %>% # create the mu, sd, q1 and q3 aggregates
  group_by(group,x)  %>%  
  summarise(mu =  round(mean(value),2), 
            sd= sqrt(round(sd(value),2)), 
            Q1 = quantile(value)[2],
            Q3 = quantile(value)[4],
            count = n())
dat
dat2 = dat %>%  gather (key = Metric, value= Value,c(mu, sd, Q1, Q3)) #melt the data
as.data.frame(dat2)
ggplot(data=dat2 , aes(x=x, y=Value, group = Metric,colour = Metric,linetype = Metric)) + 
  geom_line()  + geom_point() + ylab("value") + 
  xlab("v") + 
  scale_x_discrete(breaks = c( seq(1,5,1)  ) ) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks = c( seq(-3,3,.25)  )  ) +
  scale_colour_manual(values=c(mu = "blue", sd = "blue", Q1 = "red", Q3 = "red")) +
  scale_linetype_manual(values =c(mu = "dashed", sd= "solid", Q1 = "solid", Q3 = "solid"))  +
  facet_wrap(~ group, scales = "free",ncol=3) +
  theme(strip.text.x = element_text(size=10, angle=0),
        strip.text.y = element_text(size=12, face="bold"),
        strip.background = element_rect(colour="red", fill="#CCCCFF"))

1 个答案:

答案 0 :(得分:4)

你只需要建立一个贴标机;阅读<table>... <tr *ngFor="let obj of data"> .... </tr> ... <table> ?labeller,获取帮助。你真正需要添加的是?as_labeller(或一个适当命名的向量,构建你喜欢的方式)到labeller = as_labeller(setNames(lbl, sort(unique(group))))

facet_wrap

plot with proper facet labels