Home > Blockchain >  ggplot frequency two lines across time (month year)?
ggplot frequency two lines across time (month year)?

Time:12-09

I'm trying to graph frequency of speeches over time (time is yy-mmm), and I would like the graph to have two lines -- one for democrats and one for republicans. It should be straightforward, but I can't get it to work. Below is a sample data set and sample code for what has not worked.

myDataSet1 <- as.data.frame(cbind ("dates" = c("13-Jan", "15-Jan", "20-Jun", "13-May", 
"19-Dec"), "Party" = c("Republican", "Democrat", 
"Republican", "Democrat", "Democrat"), "Speeches" = c("2", "6", "9", "3", "6") ) )

Here's what I have tried:

ggplot(data = myDataSet1, mapping = aes(x = dates, y = Speeches, 
color = Party))   geom_line()

I get this

error: geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

EDIT -- The solution worked, but it gave me lines as well as bars. To fix it, someone suggested adding "str()" after the mutate pipe.

Here's the code I am running and having errors with:

myDataSet1 %>%
    mutate(Speeches = as.integer(as.character(Speeches)),
           dates = as.Date(paste0(dates, "-2022"), "%y-%b-%d")) %>% 
    ggplot(aes(x = dates, y = court_rhetoric, color = Party))  
    geom_line()  
    scale_x_date(date_labels = "%y-%b")

The error it gives me is:

Error in fortify():
! data must be a data frame, or other object coercible by fortify(), not an S3 object with class uneval.
Did you accidentally pass aes() to the data argument?

I also tried it piping into the ggplot and I get a different error: Error: Invalid input: date_trans works with objects of class Date only

Thanks so much for any help!

CodePudding user response:

Coerce Speeches to numeric and dates to a real date class. Then plot and set the date labels to the wanted, original format.

suppressPackageStartupMessages({
  library(dplyr)
  library(ggplot2)
})

myDataSet1 %>%
  mutate(Speeches = as.integer(as.character(Speeches)),
         dates = as.Date(paste0(dates, "-01"), "%y-%b-%d")) %>% 
  ggplot(aes(dates, Speeches, color = Party))  
  geom_line()  
  scale_x_date(date_labels = "%y-%b")

Created on 2022-12-08 with reprex v2.0.2

  • Related