Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add gradient color to line plot based on its corresponding y value using ggplot

I have a dataset that includes values for each day. I showed the sample data below:

structure(list(Global = c(-0.64, -0.52, -0.57, -0.59, -0.62, 
-0.64, -0.62, -0.58, -0.54, -0.6, -0.68, -0.68, -0.66, -0.63, 
-0.56, -0.51, -0.55, -0.61, -0.68, -0.67, -0.64, -0.57, -0.53, 
-0.62, -0.66, -0.68, -0.66, -0.63, -0.54, -0.49, -0.37, -0.66, 
-0.65, -0.61, -0.57, -0.49, -0.47, -0.67, -0.61, -0.63, -0.59, 
-0.6, -0.62, -0.45, -0.24, -0.53, -0.58, -0.58, -0.59, -0.49, 
-0.4, -0.43, -0.55, -0.53, -0.47, -0.47, -0.39, -0.34, -0.38, 
-0.49, -0.49, -0.46, -0.47, -0.39, -0.34, -0.34, -0.5, -0.51, 
-0.49, -0.43, -0.36, -0.32, -0.35, -0.44, -0.44, -0.37, -0.39, 
-0.3, -0.27, -0.27, -0.41, -0.43, -0.43, -0.38, -0.29, -0.28, 
-0.3, -0.29, -0.31, -0.33, -0.28, -0.27, -0.33, -0.14, -0.3, 
-0.34, -0.32, -0.29, -0.29, -0.27)), row.names = c(NA, -100L), class = c("tbl_df", 
"tbl", "data.frame"))

What I want to do is plot this graph such that the color of the line graph would change based on corresponding y value. This is what I have so far:

ggplot(data, aes(x=Date, y=new_global)) +
  geom_line() + 
  xlab("")+
  scale_x_date(date_labels = "%Y %b %d"

which results in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

and what I want to have is something like this:

enter image description here

As you can see, the values are in red when they are close to minimum while they are changing to green when the graph get closer to maximum value.

>Solution :

ggforce package includes geoms that can have interpolated aesthetics, like a gradient:

df %>%
  mutate(row = row_number()) %>%
  ggplot(aes(row, Global, color = Global)) +
  ggforce::geom_link2() + 
  scale_color_gradient(low = "red", high = "white") +
  theme_dark()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading