Search code examples
rggplot2rfacebook

ggplot double linechart and 3 columns


I've extracted by Rfacebook package some data about Facebook Pages. What I'm trying to get is two linecharts side by side like the attached image (a linechart for each UserName) where I can display likes, comments and shares at the same time like the attached image.

FromUser  time      shares  comments    likes
User 1    17-01-18  67      5           100
User 2    16-01-18  46      13          65
User 1    16-01-18  32      25          32
User 1    15-01-18  45      36          45
User 2    14-01-18  64      52          58

I tried with the following code but i doesn't work. Any suggestion?

line_chart <- ggplot(dataframe, aes(x = time)) + 
  geom_line(aes(y = shares), colour="blue") + 
  geom_line(aes(y = comments), colour = "grey") +
  geom_line(aes(y = likes), colour = "grey") +  
  ylab(label="Number of interactions") + 
  xlab("Days")

linechart


Solution

  • The current plot might be easier to create by rearranging your data a bit with tidyr:

    library(tidyr)
    #use gather to make a metric column
    dataframe.2 <- dataframe %>% gather(Metric, Value, -time, -FromUser)
    
    #convert date for easy ploting
    dataframe.2$time <- as.Date(dataframe.2$time , format = "%d-%m-%y")
    

    Which gives one record per user, time, and metric:

    FromUser       time   Metric Value
    User 1 2018-01-17   shares    67
    User 2 2018-01-16   shares    46
    User 1 2018-01-16   shares    32
    User 1 2018-01-15   shares    45
    User 2 2018-01-14   shares    64
    User 1 2018-01-17 comments     5
    User 2 2018-01-16 comments    13
    User 1 2018-01-16 comments    25
    User 1 2018-01-15 comments    36
    User 2 2018-01-14 comments    52
    User 1 2018-01-17    likes   100
    User 2 2018-01-16    likes    65
    User 1 2018-01-16    likes    32
    User 1 2018-01-15    likes    45
    User 2 2018-01-14    likes    58
    

    Now feed into ggplot:

    ggplot(data = dataframe.2, aes(x = time, y = Value)) + 
      geom_line(aes(color = Metric, group = Metric)) +facet_wrap(~FromUser) + 
      xlab("Date") + ylab("Number of interactions")
    

    Final Plot: enter image description here