Adding colored rectangles to a titration graph

Viewed 60

I have a data frame with a titration curve of pH, function of volume. I would like to put two colored/shadowed horizontal rectangles to show the range of pH of two indicators, methyl orange (3.2

Here is a reproducible exemple :

Volume <- c(1:5)
pH <- c(3,4,9,10,12)
df <- data.frame(Volume,pH)
ggplot(df,aes(x=Volume,y=pH))+geom_line(color="purple")+
  geom_rect(aes(ymin=3.2,ymax=4.4,xmin=-Inf,xmax=Inf))+
  geom_rect(aes(ymin=8.2,ymax=10,xmin=-Inf,xmax=Inf))+
  scale_fill_manual(values = alpha(c("orange", "pink"),alpha = .3))

Which gives me this result :

titration curve

How can theses rectangles be orange, pink and shadowed ?

2 Answers

Try this:

Volume <- c(1:5)
pH <- c(3,4,9,10,12)
df <- data.frame(Volume,pH)
ggplot(df,aes(x=Volume,y=pH))+geom_line(color="purple")+
  geom_rect(aes(ymin=3.2,ymax=4.4,xmin=-Inf,xmax=Inf), fill="orange", alpha=.3)+
  geom_rect(aes(ymin=8.2,ymax=10,xmin=-Inf,xmax=Inf), fill="pink", alpha=.3)

When something is not working, it is often a problem of referencing the wrong data or aesthetic in your geom_... calls.

Try to be very explicit when calling your geom. Below I am creating an explicit data frame for your rectangles. You should explicitly call this data and also add inherit.aes = FALSE, so that it won't try to read the aesthetic from the ggpolt main call.

library(tidyverse)

mydf <- data.frame(Volume = c(1:5), pH = c(3, 4, 9, 10, 12))

ann_rect <- bind_rows(
  data.frame(ymin = 3.2, ymax = 4.4, xmin = -Inf, xmax = Inf, fill = "orange"),
  data.frame(ymin = 8.2, ymax = 10, xmin = -Inf, xmax = Inf, fill = "pink")
)

ggplot(mydf, aes(x = Volume, y = pH)) +
  geom_rect(
    inherit.aes = FALSE,
    data = ann_rect,
    aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill)
  ) +
  geom_line(color = "purple") +
  scale_fill_identity()

Alternatively, leave the main call empty and explicitly reference the data in each geom call.


ggplot() +
  geom_rect(data = ann_rect, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill)) +
  geom_line(data = mydf, aes(x = Volume, y = pH), color = "purple") +
  scale_fill_identity()

Created on 2020-03-19 by the reprex package (v0.3.0)

Related