I generated a kind of dummy 'spaghetti plot' in R :
df <- data.frame(Id=c("A","B","C"), condition1=c(2,3,2.5), condition2=c(5,1,2.5))
library(tidyr)
df2 <- df |> pivot_longer(cols = colnames(df[,2:3]),
names_to = 'condition',
values_to = 'n')
ggplot(df2, aes(x = condition, y = n)) +
geom_line(aes(group=Id)) +
geom_point()
Now, I'd like to highlight with colors on the graph the behavior of the Ids between condition 1 and condition 2. For example, showing an increase in red and a decrease in green.
More precisely, I'd like to label for instance the line joining the points "(A,condition1)=2" to "(A,condition2)=5" in red (increase) and the line joining the points "(B,condition1)=3" to "(B,condition2)=1" in green (decrease).
I also would like to only label the condition2 points with the same color as the line, as well as adding the Id of the condition2 points always with the same color as the line. It means that the "(A,condition2)=5" point will be red, accompagnied by an "A" red label at its side. Idem for the "(B,condition2)=1" point which will be green accompagnied with an "B" green label at its side.
Bonus (cherry in the cake) will be to add a kind of arrow next to the condition2 points. The arrow will be red if there has been an increase between condition 1 and 2 for a given Id.
Do you have any ideas?
Thanks guys!
Francois
To conditionally color the line, create a new column that indicates whether the line is increasing or decreasing. Suppose you name this new column
change
, you can then modify your code as follows:geom_line(aes(group=Id, color=change))
.For the arrow question can you expand on what you mean?
As adding a text corresponding to one point, I wanted to add a small arrow, showing the trend of the line (arrow up -> increase of the line, arrow down -> decrease of the line)
Do you know how to associate the color of the line to the color of the label (with geom_label_repel for instance) ?
You can pass the same column to to the label geom,
geom_label_repel(aes(color=change))
.i just added "label = Id" before "color", and it work pretty well, thanks !
color=change gives me a continous range of colors, but I need discrete colors
What code are you using to create the new column? The result should be a character or factor to put it on a discrete color scale.
I wrote : df$change <- as.character(df$condition2 - df$condition1) instead of what I was writing before : df$change <- df$condition2 - df$condition1 and it works perfectly ! Thanks !
How to associate a color to a "change" value. For instance, if I want that a "change" value of 3 corresponds to a red line ?
You might want to instead do.
You can then manually specify the colors using
scale_color_manual
.