Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot two lines from different years in same plot using ggplot2

Tags:

r

ggplot2

charts

I'm trying to compare obama's first year approval ratings with Trump's first year approval ratings in a line chart.

The trouble here is that I use two different years obama (2009) and Trump (2017). Can't seem to figure out how to solve this...

rating_comparison %>%
  ggplot(aes(endDate, rating, group = 1)) +
  geom_line(data = filter(rating_comparison, 
                          endDate > "2017-01-28",
                          type == "Overall.A")) +
  geom_line(data = filter(rating_comparison, 
                          president == "Obama" &
                            endDate > "2009-01-25" &
                            endDate < "2010-01-24",
                          type == "Overall.A")) 

enter image description here

like image 231
Tdebeus Avatar asked Nov 18 '25 12:11

Tdebeus


1 Answers

I will assume from your code that the data looks something like this:

president   startDate    endDate  rating       type
    Obama  2017-01-17 2017-01-19      59  Overall.A
    Trump  2017-01-25 2017-01-27      42  Overall.A

I also assume that the date columns are of type Date. If not, convert them using something like:

rating_comparison$endDate <- as.Date(rating_comparison$endDate, "%Y-%m-%d")

One approach is to convert each date to "days since the first date", by president. Then plot rating versus day. Of course, this assumes that the "first dates" are somehow comparable - I assume they equate to the first polling date of each presidency.

For example, to colour by president, restricting to the first 365 days:

library(dplyr)
library(ggplot2)
rating_comparison %>% 
  filter(type == "Overall.A") %>%
  group_by(president) %>% 
  mutate(Day = as.numeric(endDate - min(endDate))) %>% 
  ungroup() %>% 
  filter(Day <= 365) %>% 
  ggplot(aes(Day, rating)) + 
    geom_line(aes(color = president))

I grabbed some Gallup data from the web, similar but not identical to yours, to get this result:

enter image description here

like image 121
neilfws Avatar answered Nov 20 '25 03:11

neilfws



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!