R ggplot2:如何根据带有 facet_wrap 的变量值命名 y 轴?

Jul*_*lia 10 r ggplot2

我会给你一个关于数据的想法,我认为这样应该更容易理解我想要实现的目标。

复制品:

ID <- c(1, 1, 2, 3, 3, 3)
cat <- c("Others", "Others", "Population", "Percentage", "Percentage", "Percentage")
logT <- c(2.7, 2.9, 1.5, 4.3, 3.7, 3.3)
m <- c(1.7, 1.9, 1.1, 4.8, 3.2, 3.5)
aggr <- c("median", "median", "geometric mean", "mean", "mean", "mean")
over.under <- c("overestimation", "overestimation", "underestimation", "underestimation", "underestimation", "underestimation")
data <- cbind(ID, cat, logT, m, aggr, over.under)
data <- data.frame(data)
data$ID <- as.numeric(data$ID)
data$logT<- as.numeric(data$logT)
data$m<- as.numeric(data$m)
Run Code Online (Sandbox Code Playgroud)

代码:

Fig <- data %>% ggplot(aes(x = logT, y = m, color = over.under)) + 
  facet_wrap(~ ID) +
  geom_point() +
  scale_x_continuous(name = "log (True value)", limits=c(1, 7)) +
  scale_y_continuous(name = NULL, limits=c(1, 7)) +
  geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
  theme_bw() +
  theme(legend.position='none')
Fig
Run Code Online (Sandbox Code Playgroud)

我想用 的值标记每个图形的 y 轴aggr。所以对于 ID 1 应该说中位数,对于 ID 2 几何平均值和 ID 3 平均值。

我尝试了多种方法:

mtext(data1$aggr, side = 2, cex=1) #or
ylab(data1$aggr) #or
strip.position = "left"
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

我也在尝试cat在图表的左上角添加。因此,对于 ID 1“其他”、ID 2“人口”和 ID 3“百分比”。我尝试与之合作,legend()但我也无法解决问题。

Stu*_*olf 9

mtext 适用于plot(). ggplot 是另一个绘图系统,所以它不会工作。不幸的是,选择不多,一种方法是删除 xlab,并将条带用作 y 轴:

LAB =tapply(as.character(data$aggr),data$ID,unique)

Fig <- data %>% ggplot(aes(x = logT, y = m, color = over.under)) + 
  geom_point() +
  scale_x_continuous(name = "log (True value)", limits=c(1, 7)) +
  scale_y_continuous(name = NULL, limits=c(1, 7)) +
  geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
  theme_bw() +
  theme(legend.position='none') +
  facet_wrap(~ID, scales = "free_y",strip.position = "left", 
  labeller = as_labeller(LAB ))  +
  ylab(NULL) +
  theme(strip.background = element_blank(),strip.placement = "outside")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

另一种方法是组合图:

library(gridExtra) 

plts = by(data,data$ID,function(i){
ggplot(i,aes(x=logT,y=m,color=over.under)) + 
geom_point() + 
scale_x_continuous(name = "log (True value)", limits=c(1, 7)) +
scale_y_continuous(name = unique(i$agg), limits=c(1, 7)) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
theme_bw() + 
scale_color_manual(values=c("overestimation"="turquoise","underestimation"="orange"))+
theme(legend.position='none') 
})

grid.arrange(grobs=plts,ncol=3)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明