1

I would like to have a line plot where I have 2 lines with 2 different color and each line would have sections colored in different shades of that color. Like a gradient shade for each line. e.g. a line with shades of blue for different regions along the x-axis

library(ggplot2) df <- data.frame(a = c(rep(0,10), rep(1,10)), b = c(rep(c(rep(0,3),rep(1,4),rep(2,3)), 2)), c = sample(1:20), d = c(1:20)) df ggplot(data = df) + geom_line(aes(x = d, y = c, color = factor(a), linetype = factor(b))) 

enter image description here Here I get each line with different color. Tried adding a different linetype to each section but that doesn't work. Each line should by itself have different shades based on column b

2 Answers 2

1

You can try using alpha and line size instead of linetype.

Code:

library(ggplot2) ggplot(df) + geom_line(aes(d, c, color = factor(a), group = a, size = factor(b), alpha = factor(b))) + scale_alpha_manual(values = c(1, 0.6, 0.2)) + scale_size_manual(values = c(2, 1, 0.5)) 

Result:

enter image description here


Data (df):

structure(list(a = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), b = c(0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2), c = c(6L, 13L, 10L, 20L, 2L, 11L, 15L, 5L, 3L, 7L, 17L, 4L, 12L, 14L, 1L, 19L, 9L, 8L, 18L, 16L), d = 1:20), .Names = c("a", "b", "c", "d"), row.names = c(NA, -20L), class = "data.frame") 
Sign up to request clarification or add additional context in comments.

6 Comments

good solution buddy ! I still would have first preference for different shades as the number of levels here is 5. Hence thicker lines makes plot too dense
@joel.wilson doesn't alpha give your different shades?
it does. But very very light. Can we tweak it to get little darker shades?
Make the colors darker to then give darker shades
thanks bro ! I played around with this and it worked!!
|
0

How about this approach:

create a ramp from blue to red of 8 colors used first 3 colors to map the blues and last three to map the reds. Color based on interaction of a and b:

colfunc <- colorRampPalette(c("blue", "red")) ggplot(data = df)+ geom_line(aes(x = d, y = c, color = interaction(b, a), group = a)) + scale_color_manual(values = colfunc(8)[c(1:3,6:8)]) 

enter image description here

or something along these lines:

bfunc <- colorRampPalette(c("blue3", "dodgerblue", "firebrick1", "darkred")) ggplot(data = df)+ geom_line(aes(x = d, y = c, color = interaction(b, a), group = a)) + scale_color_manual(values = bfunc(6)) 

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.