ggplot-在图形顶部添加框

时间:2018-12-02 13:33:08

标签: r ggplot2 box

我有以下数据和图表:

 fixed <- as.data.frame(rep(0.125,8))
fixed[,2] <- c("1","2","3","4","5","6","7","8")
colnames(fixed) <- c("Percentage", "Test")

enter image description here

是否可以将均值添加为图形上方的单独框?我不想共享相同的y轴,因为这可能会与标签混淆。

这里是我正在寻找的示例。如果我也可以将框的背景也涂得更深,那是可能的:

enter image description here

这是我的情节的代码:

p <- ggplot(fixed,aes(x=Test ,y=Percentage,fill=Test))+
  geom_boxplot()+ 
  stat_summary(fun.data = function(y) 
    data.frame(y=0.6, label = paste(round(mean(y),2))), geom="text",size=3) +
  geom_hline(yintercept=0.55, linetype="dashed", color = "black")+
  theme(legend.position="none")+
  scale_y_continuous(limits = c(0, 0.6),breaks=seq(0,0.6,0.1),
                     labels= c("0%","10%","20%","30%","40%","50%","Mean"))+
  theme_bw()+
  labs(title = "Title")+
  xlab("Test")+
  ylab("Percetage")+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_rect(fill = "grey90", colour = NA),
        plot.background = element_rect(fill = "grey90", colour = NA),
        legend.position="none",plot.title = element_text(size= 12, hjust=0.5),
        plot.margin = unit(c(1,1,1,1), "cm"))+
  scale_fill_manual(values=c("#00441b","#006d2c","#238b45","#41ab5d","#74c476",
                             "#a1d99b","#c7e9c0","#e5f5e0"))
p

1 个答案:

答案 0 :(得分:1)

fixed <- as.data.frame(rep(0.125, 8))
fixed[, 2] <- c("1", "2", "3", "4", "5", "6", "7", "8")
colnames(fixed) <- c("Percentage", "Test")

让我们在ggplot2版本中添加一些结构。并且,我们将一些dataaes()直接移到stat_geom_ s上,这样我们就可以做er了, {{1 }} 注释。注释在显着行中/附近:

geom_rect()

enter image description here