R: Line graph with a color gradient using ggplot2

This tutorial provides a way to plot a line graph with ggplot2 with ga color gradient

Yedomon Ange Bovys Zoclanclounon https://yedomon.netlify.app/ (Jeonbuk National University)http://www.jbnu.ac.kr/eng/
01-10-2021

Brainstorming

The purpose here is to plot a line graph that shows the nucleotide diversity (Pi) alongside a chloroplast genome. More specifically, we want to emphasis using a gradient color a certain value up to a threshold (here 0.015).

Let’s get into it!

Solution

Package loading

Data importaion

data_pi = read.table("C:/Users/ange_/Downloads/My website/data.csv", sep = ";" , h = T)

Our data looks like this…

Let’s write the code

ggplot(data_pi, aes(x=Position, y=Pi, colour = Pi)) +
  
  geom_line() +
  
  scale_colour_gradient2(low = "#0000b3", mid = "#3333ff" , high = "#ff0000", midpoint=0.015) +
  
  geom_hline(yintercept=0.015, color="#00b300", size=.4, linetype = "dotted") +
  
  labs(y = expression(Nucleotide~diversity~(pi)), x = "Nucleotide position") +
  
  theme_minimal()+
  theme(panel.grid.major = element_line(colour = "grey", size = 0.2, linetype = "dotted")) +
  theme(panel.grid.minor = element_line(colour = "grey", size = 0.2, linetype = "dotted")) +
  theme(plot.background = element_rect(colour = "white", size = 1))+
  theme(axis.text = element_text(colour = "black")) +
  
  scale_x_continuous(limits=c(0,155000),
  breaks = seq(0, 155000, by = 25000)) +
  scale_y_continuous(limits=c(0,0.035),
                     breaks = seq(0, 0.035, by = 0.005))

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

Citation

For attribution, please cite this work as

Zoclanclounon (2021, Jan. 10). Diary of an Autodidact: R: Line graph with a color gradient using ggplot2. Retrieved from https://yedomon.netlify.app/posts/2021-01-10-r-line-graph-with-a-color-gradient-using-ggplot2/

BibTeX citation

@misc{zoclanclounon2021r:,
  author = {Zoclanclounon, Yedomon Ange Bovys},
  title = {Diary of an Autodidact: R: Line graph with a color gradient using ggplot2},
  url = {https://yedomon.netlify.app/posts/2021-01-10-r-line-graph-with-a-color-gradient-using-ggplot2/},
  year = {2021}
}