Home > Mobile >  Different vertical line for each facet in ggplot
Different vertical line for each facet in ggplot

Time:03-08

I would like to display in each facet of a ggplot figure a vertical bar with the mean of the data in the facet. I can do this for an individual facet :

# For Petal Length Only :
Mean <- colMeans(iris["Petal.Length"])
iris %>% pivot_longer(cols = !Species,names_to = "Characteristic",values_to = "Value") %>% 
  filter(Characteristic=="Petal.Length") %>%
  ggplot(aes(x=Value,fill=Species)) geom_density() facet_wrap(~Characteristic) 
geom_vline(xintercept = Mean)

But when doing it with facets, 4 vertical lines are displayed instead of one for each facet :

# For all characteristics :
Mean <- colMeans(iris[-5])
iris %>% pivot_longer(cols = !Species,names_to = "Characteristic",values_to = "Value") %>%
  

ggplot(aes(x=Value,fill=Species)) geom_density() facet_wrap(~Characteristic) geom_vline(xintercept = Mean)
# Display vertical lines for all means where I would like only one vertical bar
# by group displayed (one for petal length, one for sepal width, etc)
 
# for example for Petal Length, only the vertical line with intercept colMeans(iris["Petal.Length"]) should be displayed.
 

enter image description here

CodePudding user response:

The issue was with that 'Mean' variable. Its format is not consistent with primary dataset. Structure it in the same way and the faceting will work as expected.

library(dplyr)
library(tidyr)
library(ggplot2)
# For all characteristics :
Mean <- colMeans(iris[-5]) %>% as_tibble(rownames = "Characteristic")
iris %>% pivot_longer(cols = !Species,names_to = "Characteristic",values_to = "Value") %>%
  ggplot(aes(x=Value,fill=Species)) 
  geom_density() 
  geom_vline(aes(xintercept = value),data=Mean)  
  facet_wrap(~Characteristic) 
  • Related