I have a dataset of multiple measurements that were taken under two different conditions. I graphed each dataset on the same graph and used a different color palette for the different conditions the data was gathered under. I’ve also joined all the sets of data so that they are in a single dataframe that looks like this:
device1 condition1 | device2 condition1 | device1 condition2 | device2 condition2 | n |
---|---|---|---|---|
10 | 20 | 20 | 40 | 1 |
30 | 40 | 60 | 80 | 2 |
After running the below code I ended up with the subsequent graph:
#counter = number of devices being measured
counter <- length((merged_data) - 1) / 2 #the formula is different in my actual code but this number is equivalent
blue_shades <- scales::seq_gradient_pal("blue", "lightblue")(seq(0, 1, length.out = counter))
red_shades <- scales::seq_gradient_pal("red", "lightcoral")(seq(0, 1, length.out = counter))
plot_graph <- ggplot(data = merged_data)
for (i in seq_len(counter)) {
# Blue shades for condition1, Red shades for condition2
plot_graph <- plot_graph +
geom_line(aes(y = .data[[names(merged_data)[i]]], x = n), color = blue_shades[i], linewidth = if (i == 1) 1.75 else 0.75) +
geom_line(aes(y = .data[[names(merged_data)[counter + i]]], x = n), color = red_shades[i], linewidth = if (i == 1) 1.75 else 0.75)
}
plot_graph <- plot_graph +
ylab("y") +
xlab("x")
I want to add a legend to this plot that will show the name of the column and the color that represents it on the graph, but I’m not sure how to do this. I tried moving the color field to be inside aes, as shown below, but that produced different incorrect plot (also shown below)
plot_graph <- plot_graph +
geom_line(aes(y = .data[[names(merged_data)[i]]], x = n, color = blue_shades[i]), linewidth = if (i == 1) 1.75 else 0.75) +
geom_line(aes(y = .data[[names(merged_data)[counter + i]]], x = n, color = red_shades[i]), linewidth = if (i == 1) 1.75 else 0.75)
Does anyone have any ideas of how I can fix this and get the proper colors and legend?
2