Home > Enterprise >  Sample comparison with ggplot2
Sample comparison with ggplot2

Time:09-28

In this example, I want compare population in USA versus China, over time.

library(tidyverse)

population %>%
  filter(country %in% c("United States of America", "China")) %>%
  pivot_wider(names_from = country, values_from = population) %>%
  rename(USA = `United States of America`) %>%
  ggplot(aes(x = China, y = USA))   geom_point(aes(col = year))

Is there a better way to do this (without using pivot_wider)? Or is this the right way?

Thanks in advance

CodePudding user response:

Not sure if this is still what you want, but I'd expect th comparison between two population sizes over time to look something like this:

library(ggplot2)
library(dplyr)

population %>%
  filter(country %in% c("United States of America", "China")) %>%
  ggplot(aes(x = year, y = population, color=country))  
  geom_line()  
  expand_limits(y=0)

Returns:

enter image description here

CodePudding user response:

It is the right way if you want to show how the population of USA varies as a function of the population of China... but what's the sense of it? Probably what you want is to compare how the two population change as a function of time, then I think you'd be better off with a bar chart:

library(tidyverse)
population %>%
  filter(country %in% c("United States of America", "China")) %>%
  ggplot(aes(x = year, y=population, fill=country))   
  geom_col(position="dodge")

Created on 2021-09-28 by the reprex package (v2.0.1)

  • Related