0

I want to add horizontal line to a facetted barplot using ggplot2.

I have two nutrient types, each with a different guideline value I would like to display and I want the plots to appear side by side in a single frame.

Data looks like this:

Trip   Depth       NutrientType   ugL
  <fct>  <fct>       <chr>        <int>
1 Before Surface     TN            1111
2 Before Surface     TP             162
3 Before Near bottom TN            1428
4 Before Near bottom TP             191
5 After  Surface     TN             869
6 After  Surface     TP             756
7 After  Near bottom TN             816
8 After  Near bottom TP             487

Current code:

BARR1plot <- ggplot(
  BARR1,
  aes(
    x = Depth,
    y = ugL,
    fill = Trip
  )
) +
  geom_bar(colour = "black", stat = "identity", position = "dodge") +
  scale_fill_manual(values = colours) +
  theme_classic() +
  theme(text = element_text(size = 18)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) +
  theme(axis.title.y = element_text(size = 16)) +
  theme(legend.title = element_blank()) +
  ylab("Concentration (µg/L)") +
  xlab("") +
  facet_grid(~NutrientType, scales = "fixed", switch = "x") +
  labs(title = "BARR1") +
  theme(plot.title = element_text(hjust = 0)) +
  theme(panel.spacing = unit(0, "mm"))

I have searched through previous questions and added code to my existing plot code using geom_hline but both lines appear across both plots rather than just with their associated nutrient type.

Currently using this code:

data_hline <- data.frame(
  group = unique(BARR1$NutrientType),
  hline = c(900, 250)
)

BARR1plot +
  geom_hline(
    data = data_hline,
    aes(yintercept = hline)
  )

But get this result:

Plot

stefan
  • 90,330
  • 6
  • 25
  • 51
Lindsey
  • 1
  • 1

1 Answers1

0

The issue is that you facet by NutrientType but in the data for the geom_hline you named the column containing the nutrient type group. Hence, this data will not be facetted and both lines will be displayed in both facet panels.

To fix that rename your column.

library(ggplot2)

data_hline <- data.frame(
  NutrientType = unique(BARR1$NutrientType),
  hline = c(900, 250)
)

BARR1plot +
  geom_hline(
    data = data_hline,
    aes(yintercept = hline)
  )

enter image description here

DATA

BARR1 <- structure(list(Trip = c(
  "Before", "Before", "Before", "Before",
  "After", "After", "After", "After"
), Depth = c(
  "Surface", "Surface",
  "Near bottom", "Near bottom", "Surface", "Surface", "Near bottom",
  "Near bottom"
), NutrientType = c(
  "TN", "TP", "TN", "TP", "TN",
  "TP", "TN", "TP"
), ugL = c(
  1111L, 162L, 1428L, 191L, 869L, 756L,
  816L, 487L
)), class = "data.frame", row.names = c(
  "1", "2", "3",
  "4", "5", "6", "7", "8"
))
stefan
  • 90,330
  • 6
  • 25
  • 51