0

I have a dataframe in R. First column is date. The rest columns are data for each category.

        Date View1 View2 View3 View4 View5 View6 
1 2010-05-17    13   10   13   10     13     10
2 2010-05-18    11   11   13   10     13     10
3 2010-05-19     4   12   13   10     13     10
4 2010-05-20     2   10   13   10     13     10
5 2010-05-21    23   16   13   10     13     10
6 2010-05-22    26   15   13   10     13     10

How can plot a timeplot with two lines? Each line for each column. i.e one line for View1, one line for View2, one line for View3 and so on. The x-axis is Date. Is there a function in ggplot can achieve this easily?

I searched other posts, see a solution below, but it gives me nothing on the plot.

mydf %>% gather(key,value, View1, View2, View3, View4, View5, View6 )  %>% ggplot(aes(x=Date, y=value, colour=key))

I also tried the commands below.

test_data_long1 <- melt(mydf, id="Date") 
ggplot(data=test_data_long1,
       aes(x=date, y=value, colour=variable)) +
       geom_line()

It gives me an error.

Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Error: All columns in a tibble must be 1d or 2d objects:
* Column `x` is function
AAA
  • 695
  • 1
  • 7
  • 21
  • 1
    Here's a similar question that might help: https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph?rq=1 – Jon Spring Jun 14 '19 at 23:00
  • `autoplot.zoo` can do this easily. `library(ggplot2); library(zoo); z <- read.zoo(mydf); autoplot(z, facet = NULL)` Omit the `facet` argument if you want separate panels. See `?autoplot.zoo` for more info. – G. Grothendieck Jun 15 '19 at 12:44

1 Answers1

0

You coud just rewrite a dataframe for plotting:

dates <- c("2010-05-17", "2010-05-18", "2010-05-19", "2010-05-20", "2010-05-21")
df<- data.frame(date = dates, view1 = sample(10:15, 5, replace = TRUE), 
            view2 = sample(10:15, 5, replace = TRUE), 
             view3 = sample(10:15, 5, replace = TRUE), 
              view4 = sample(10:15, 5, replace = TRUE))
df$date <- as.Date(df$date)

toPlot1 <- df[,c(1,2)]
toPlot1[,3] <- "view1"
names(toPlot1) <- c("date", "n", "view")

toPlot2 <- df[,c(1,5)]
toPlot2[,3] <- "view4"
names(toPlot2) <- c("date", "n", "view")

toPlot<-bind_rows(toPlot1, toPlot2)

The graph would be the following:

ggplot(toPlot, aes(date, n, linetype = view)) + geom_line()

Or, using the reshape2 package you could just melt the data:

library(reshape2)

meltedDf <- melt(df ,  id.vars = 'date', variable.name = 'series')

ggplot(meltedDf, aes(date, value, linetype = series)) + geom_line()