Stephen Williams Stephen Williams - 16 days ago 5
R Question

Single vertical lines in ggplot2 facet

I have a dataframe with some simple information. A sample code (A,C,T,or, G) and some counts for each sample. I also have a dataframe with some means that I want to plot as vertical lines for each code. Unfortunately, when I make the plot all means show up on all plots. Is there any way to plot one vertical line on one plot in order?

Many thanks and a simple example below

dummy data

sample <- c(1:100)
code <- c(rep("A", 25), rep("C", 25),rep("G", 25),rep("T", 25))
count <- sample(1:30, 100, replace=T)
df <- data.frame(sample, code, count)


vline.data <- data.frame(z = c(15, 20, 25, 30))

ggplot(df, aes(x=count))+
geom_histogram(binwidth=.5)+
facet_grid(. ~ code)+
geom_vline(aes(xintercept = z), vline.data)+
theme(axis.title.x=element_text(),
axis.title.y=element_text(),
legend.position="none")

Answer

Maybe this?:

sample <- c(1:100)
code <- c(rep("A", 25), rep("C", 25),rep("G", 25),rep("T", 25))
count <- sample(1:30, 100, replace=T)
df <- data.frame(sample, code, count)

library(dplyr)

vline.data <- df %>%
              group_by(code) %>%
              summarize(z = mean(count))

ggplot(df, aes(x=count))+
  geom_histogram(binwidth=.5)+
  facet_grid(. ~ code)+
  geom_vline(aes(xintercept = z), vline.data, colour = "red")+
  theme(axis.title.x=element_text(),
        axis.title.y=element_text(),
        legend.position="none")

enter image description here