0

I'm trying to draw three lines per group using ggplot in R. I'd like to change the second and third lines per group to dashed lines. So, "Blacks" and "Whites" per gene will be dashed lines, only "All" group per gene will have a solid line. However, I have no idea on how to do this.

Please help me with this.

Here are the example codes. Please never mind the dots outside of the lines. It was supposed to be beta and 95% CI. I just created dummy numbers for this issue.

beta <- runif(9)
lower <- runif(9)
upper <- runif(9)
gene <- rep(c(letters[1:3]), times=3)

sample.data <- data.frame(cbind(beta, lower, upper, gene))
sample.data$group<-rep(c("all", "blacks", "whites"), each=3)

cols <- colnames(sample.data)[1:3]
sample.data[cols] <- sapply(sample.data[cols], as.numeric)

p <- sample.data %>% mutate (group = as.factor(group)) %>%
  ggplot(aes(x=gene, y=beta, colour=group)) +
  geom_point(aes(x=gene, y=beta), size=2.2, position = position_dodge(width = 0.5)) +
  geom_errorbar(aes(x=gene, ymin=lower, ymax=upper), size=0.7, width=0.4, position = position_dodge(width = 0.5))+
  theme_bw() + 
  theme(axis.text.x = element_text(size=10, angle = 45, vjust = 0.9, hjust=0.95)) +
  theme(axis.text.y = element_text(size=11)) +
  guides(color=guide_legend("Group")) + scale_color_hue(labels = c("ALL", "Blacks", "Whites"))
dbfk2000
  • 15
  • 3
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jan 06 '23 at 21:37
  • @MrFlick Yes, I was in the middle of editing when you left the comment. Please take a look again. Thanks in advance! – dbfk2000 Jan 06 '23 at 21:43
  • @MrFlick I revised the body to make it clear. I want to have the dashed lines for Blacks and Whites, and the solid line for ALL group per gene on x-axis. – dbfk2000 Jan 06 '23 at 21:56
  • Use `geom_errorbar(aes(x=gene, ymin=lower, ymax=upper, linetype=group), ...)` to change the line type based on group, then use `scale_linetype(breaks=c(1,2,2))` to make sure they use the same dashed line – MrFlick Jan 06 '23 at 21:59

0 Answers0