Home > OS >  Connecting Dots for Every Person: Ggplot
Connecting Dots for Every Person: Ggplot

Time:07-19

I have this dataset:

my_data = data.frame(name = c("person1", "person2", "person3", "person4", "person5"), val_2015 = rnorm(5,10,1), val_2016 = rnorm(5,15,1), val_2017 = rnorm(5,15,1), val_2018 = rnorm(5,20,1), val_2019 = rnorm(5,20,1), val_2020 = rnorm(5,25,1))

    name  val_2015 val_2016 val_2017 val_2018 val_2019 val_2020
1 person1 10.791620 15.53671 15.21501 19.72177 19.21759 24.85471
2 person2 10.886296 16.77685 13.71786 19.92509 21.37132 24.56139
3 person3  9.983005 15.11207 13.76680 20.01850 21.33288 25.73419
4 person4 12.085364 15.06255 14.21242 18.95248 18.68955 25.70048
5 person5 10.935243 14.42383 15.41543 19.12219 19.40416 24.36996

I am trying to make a time series plot for this data in which:

  • The x-axis is the year (2015, 2016, 2017, 2018, 2019, 2020)
  • The y-axis is the "value"
  • And there are 5 trend lines - one line for each person

I tried to do this by reshaping the data - and trying to plot the graph:

library(ggplot2)

final = reshape2::melt(my_data, id.var = "name")

ggplot(final, aes(x = name, y = value, colour = variable, group = name))   
    geom_point()   
    geom_line()

enter image description here

But this is looking nothing like the expected result : not only are the lines connected kin the wrong way, the data is being graphed for each column instead of each person! How can I fix this problem?

Thank you!

CodePudding user response:

It sounds like you want

ggplot(final, aes(x = variable, y = value, colour = name, group = name))   
    geom_point()   
    geom_line()

enter image description here

  • Related