在 geom_bar ggplot2 中操作 scale_y_log

manipulate scale_y_log in geom_bar ggplot2

我有以下 df 作为示例:

sites <- c('s1','s1','s2', "s2", "s3", "s3")
conc  <- c(15, 12, 0.5, 0.05, 3, 0.005)
trop  <- c("pp", "pt")

df <- data.frame(sites, conc, trop)
df$trop<- factor(df$trop, levels = c("pp", "pt"))

ggplot(df, aes(x= sites, y= conc))+
  geom_bar(stat = "identity", colour="black")+
  scale_y_log10()+
  facet_grid(.~trop)+
  theme_bw()

结果如下图,这对我的数据分析很有帮助,因为我想突出显示值大于 1 的站点。

然而,在另一个假设下,我需要使用 facet_grid 突出显示 1 和 0.1 以上的站点,最后得到这样的结果(我将此图编辑为期望输出):

你知道 scale_y_log10 中的任何选项以获得 facet_grid 下的第二个数字吗?

一个选项是将条形重新参数化为矩形并绘制它。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.3

sites <- c('s1','s1','s2', "s2", "s3", "s3")
conc  <- c(15, 12, 0.5, 0.05, 3, 0.005)
trop  <- c("pp", "pt")

df <- data.frame(sites, conc, trop)
df$trop<- factor(df$trop, levels = c("pp", "pt"))

char2num <- function(x){match(x, sort(unique(x)))}

ggplot(df) +
  geom_rect(
    aes(
      xmin = char2num(sites) - 0.4,
      xmax = char2num(sites) + 0.4,
      ymin = ifelse(trop == "pt", 0.1, 1),
      ymax = conc
    ),
    colour = 'black'
  ) +
  scale_y_log10() +
  # Fake discrete axis
  scale_x_continuous(labels = sort(unique(df$sites)),
                     breaks = 1:3) +
  facet_grid(. ~ trop) +
  theme_bw()

reprex package (v1.0.0)

于 2021 年 2 月 26 日创建