user2522217
user2522217

Reputation: 355

How to graph multiple lines in a single plot ggplot2?

I'm working on a R Shiny program that can take any csv file and output graphs of it. The user who uploads the csv has some guidelines on how the data should look, but I don't want it to be too strict.

I'm currently trying to use ggplot2 to graph multiple lines of the same dataset on one plot for comparison.

The data I am currently uploading looks like this (simplified, as the data has over 1000 rows):

Date Hamburgers Salads Sodas Fries
12-01    4        4      3    2
12-02    1        7      3    9
12-03    22       24     45   34
12-04    23       44    46    22

I'm trying to output a graph that has the time on the X-axis (the user chooses this via a sidebar, as he can choose any axis, but time makes the most sense here). For the Y axis, I want 4 lines, colored differently, plotting each variable over time.

I have all of the 'user taking in input and choosing which columns to graph' implemented, but for simplicity's sake, we can assume that for the most part, this has been hard coded (so Y variable will actually be input$y, etc in my implementation)

The portion of my code where I try to graph the data is:

output$plotLine <- renderPlot({
  p <- ggplot(data, aes_string(x=X, y=Y), environment = environment()) 
      p <- p + geom_point(size = 3) 
      p <- p + geom_line(aes(group=1)) 

  print(p)
})

This plots one of the lines, but I have no idea how to plot the others on the same plot. I've read about using 'group' in the aes function, but this depends on having a classifier in the dataset, which this one currently does not have.

I have also looked into the melt() function from the reshape2 package but am not sure how it would help me (both for the multiple line problem and the greater sense of this project, so that the user doesn't have to abide by strict rules for upload format of the csv).

Any help would be much appreciated!

Upvotes: 0

Views: 4616

Answers (1)

Aert
Aert

Reputation: 2049

Assuming you put the xaxis variable (Date) in selectedxaxis, the selected products in selectedproducts and with data holding the loaded data:

selectedxaxis = "Date"
selectedproducts = c("Sodas", "Salads")
widedata = subset(data, select = c(selectedxaxis, selectedcolumns))

longdata = melt(widedata, id.vars=selectedxaxis, variable.name='Product', value.name='Count')
ggplot(longdata) + geom_line(aes(Date, Count, color=Product))

Upvotes: 1

Related Questions