how can I plot two graphs in one coordinate system combining all the values of one column?

Viewed 72

I want to have one coordinate system but here is the problem:

I have all the graphs from all my states in the dataset, in the right colors and in the legend only according to party, but still, it's 50 graphs. I want only two - one combining all the republican states and one combining all the democratic states.

corona_usa_simple <- readr::read_csv("https://raw.githubusercontent.com/datasets/covid-19/master/data/us_simplified.csv")

corona_us_states <- corona_usa_simple %>% 
select(- FIPS, -`Country/Region`) %>%  rename(State=`Province/State`)

us_states_population <- corona_us_states %>%
    group_by(State, Date) %>% 
    summarise(totalPopulation = sum(Population),
              totalConfirmed = sum(Confirmed),
              totalDeaths = sum(Deaths))

wiki_governors <- htmltab("https://en.wikipedia.org/wiki/List_of_United_States_governors",
 header = 2) %>% slice(-1)
wiki_governors[23,3] <- "Democratic" #Democratic-Farmer-Labor to Democratic

corona_party_states <- left_join(wiki_governors, us_states_population, by= "State") %>%
select(- Governor, - Born, - `Prior public experience`, - Inauguration, - `End of term`, - `Past governors`)
corona_party_states <- transform(corona_party_states, CasesPop = totalConfirmed*100000/totalPopulation) %>%
  rename(state = State) 

## Plot for the graphs
ggplot(data = corona_party_states) +
  geom_point(aes(x = Date, y = CasesPop, color = Party)) +
  scale_color_manual(values=c("Democratic" = "blue", "Republican" = "red"))+
  ggtitle("COVID-19 Cases per Capita by Party")+
  ylab("Cases/100K")+
  xlab("Timeline")+
  theme_bw()

This is my code so far. I would appreciate any help!

I also tried this approach, but it looks just the same:

corona_party_cases <- corona_party_states %>% 
 group_by(Party, Date) %>% select(-state) %>% summarise(CasesPop)
1 Answers

If I understand you correctly, you want two lines on your plot; one line for cases per 100,000 in Republican states and one for cases per 100,000 in Democrat states. This being the case, you have a bit more work to do on your data to clean and summarise it. The plotting code itself is fine.

corona_party_states %>% 
  select(-Party) %>% 
  rename(Party = Party.1) %>%
  mutate(Party = substr(Party, 1, 10)) %>%
  group_by(Date, Party) %>%
  summarise(total_pop = sum(totalPopulation),
            total_confirmed = sum(totalConfirmed),
            CasesPop = 100000 * total_confirmed/total_pop) %>%
  ggplot() +
  geom_line(aes(x = Date, y = CasesPop, color = Party), size = 2) +
  scale_color_manual(values = c(Democratic = "blue", Republican = "red")) +
  ggtitle("COVID-19 Cases per Capita by Party")+
  ylab("Cases/100K")+
  xlab("Timeline")+
  theme_bw()

enter image description here

Related