0

I have the following df as example:

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()

which gives as results the following figure, which is quite helpful for my data analysis since I want to highlight sites with values above 1.

enter image description here

However, under another assumption, I need to highlight sites above 1 and 0.1 using facet_grid, ending up with something like this (I edited this figure as desire output):

enter image description here

Do you know any option in scale_y_log10 in order to get the second figure under facet_grid?

Pedr Nton
  • 79
  • 7
  • What do you mean by "I need to highlight sites above 1 and 0.1"? if what you need is just to arrange 2 plots use the `patchwork` package: `library(patchwork);p1 / p2` (`p1` being the top plot, `p2` being the bottom plot) – Oliver Feb 26 '21 at 14:25
  • Does this answer your question? [How to start ggplot2 geom\_bar from different origin](https://stackoverflow.com/questions/48794575/how-to-start-ggplot2-geom-bar-from-different-origin) – Limey Feb 26 '21 at 14:25

1 Answers1

1

One option is to reparameterise the bars as rectangles and plot that instead.

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()

Created on 2021-02-26 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • When I have two levels, your reply is extremely useful. However, I am struggling when `trop <- c("pp", "pt","pd")`. I tried this `ymin = ifelse(trophic_fct == c("pt", "pd") , c(0.1,0.1, 1))` but I received the following `Error: `breaks` and `labels` must have the same length` May you give a hint to solve out this new issue? – Pedr Nton Mar 01 '21 at 09:28
  • 1
    You might want to replace the `==` operation with the `%in%` operation because you cannot vectorise the `==` operation if the variables on both sides are of unequal length or not of length 1. – teunbrand Mar 01 '21 at 10:00