A problem occurs when i add a colour(gradient) into the aesthetics of geom_line. It seems that the dots are no longer connected by a line but instead transformed into squares, which messes up the plot. Does anyone have an idea how to solve this problem or if this is how R or ggplot handles colour(gradients). This problem doesn't occur, when i remove the colours from the aes().
Thanks in advance!
Simple code:
df <- data.frame(c(1,3,4,2,5,8),c(1,2,3,4,5,6))
colnames(df) <- c("x","y")
ggplot()
theme_classic()
geom_line(data=df,aes(x=x,y=y,colour=y),size=2)
ggplot()
theme_classic()
geom_line(data=df,aes(x=x,y=y),size=2)
CodePudding user response:
Adjusting the lineend
parameter should do it, which has a default of "square". The reason the uncolored version looks okay is that in those cases the segments are treated as continuations of the same series, so they are governed then by the linejoin
parameter, which has a default of "round."
ggplot()
theme_classic()
geom_line(data=df,aes(x=x,y=y,colour=y),size=2, lineend = "round")
PS - if you want the color to vary within each segment, you might look at alternatives like ggforce::geom_link2
, which uses interpolation to allow smooth transitions. However, it's parameterized differently, to be like geom_path, which plots data in order of appearance rather than in order of the x
value, like geom_line
.