When plotting with ggplot, I often have to transforme the data into the long format, for example, like in the code below. Two questions arise for me:
- Is there a way to use the column (so each variable) as a "group"? So each column is plotted and has a different color? Hence it would not be necessary to transform the data to the long format. (Without putting every variable into a
geom_line()) - Why is it the case that you have to transform the data into the long format? What is the reason behind it? How is it better than plotting when your data has the wide format?
The example code:
library(tidyverse)
# Data in wide format
df_wide <- data.frame(
Horizons = seq(1,10,1),
Country1 = c(2.5, 2.3, 2.2, 2.2, 2.1, 2.0, 1.7, 1.8, 1.7, 1.6),
Country2 = c(3.5, 3.3, 3.2, 3.2, 3.1, 3.0, 3.7, 3.8, 3.7, 3.6),
Country3 = c(1.5, 1.3, 1.2, 1.2, 1.1, 1.0, 0.7, 0.8, 0.7, 0.6)
)
# Convert to long format
df_long <- df_wide %>%
gather(key = "variable", value = "value", -Horizons)
# Plot the lines
plotstov <- ggplot(df_long, aes(x = Horizons, y = value)) +
geom_line(aes(colour = variable, group = variable))+
theme_bw()

