priya
priya

Reputation: 105

how to visualize line chart in R using ggplot having date

I have following data set and I want to visualize it in Line chart or any thing using ggplot in R

 Date                    x       y       Total       
2019-06-02               23      45        68
2019-06-03                0      72        72 
2019-06-04               54      10       156
2019-06-05               62      21        83

I want to visualize data, x, y columns in line chart using ggplot in R. Thank you

Upvotes: 0

Views: 79

Answers (1)

Duck
Duck

Reputation: 39595

Try this tidyverse approach with ggplot2. You have to reshape your data to long. Also as yu want dates, be sure you have your variable in date format. You only want x and y so you can add a filter() statement to only consider those variables. With data in that format is possible to get a plot as you want:

library(tidyverse)
#Code
df %>% mutate(Date=as.Date(Date,'%d/%m/%Y')) %>%
  pivot_longer(-c(Date)) %>%
  filter(name!='Total') %>%
  #Sketch the plot
  ggplot(aes(x=Date,y=value,group=name,color=name))+
  geom_line()

Output:

enter image description here

Some data used:

#Data
df <- structure(list(Date = c("02/06/2019", "03/06/2019", "04/06/2019", 
"05/06/2019"), x = c(23L, 0L, 54L, 62L), y = c(45L, 72L, 102L, 
21L), Total = c(68L, 72L, 156L, 83L)), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 1

Related Questions