Home > Software engineering >  R: Guessing the "Format" of a Dataset?
R: Guessing the "Format" of a Dataset?

Time:12-06

I am working with the R programming language.

I am trying to follow this tutorial here enter image description here

Can someone please show me what I am doing wrong and what I can do to fix this problem?

Thanks!

CodePudding user response:

Fix the scale of your data by multiplying the values by e.g. 4e4 and make the values for males negative:

library(tidyverse)
library(extrafont)

set.seed(123)

vn_2018_pop$Value <- 4e4 * vn_2018_pop$Value
vn_2018_pop$Value[vn_2018_pop$Gender == "M"] <- -vn_2018_pop$Value[vn_2018_pop$Gender == "M"]

my_colors <- c("#2E74C0", "#CB454A")
my_font <- "Roboto Condensed"

vn_2018_pop %>% ggplot(aes(Age, Value, fill = Gender))  
  geom_col(position = "stack")  
  coord_flip()  
  scale_y_continuous(
    breaks = seq(-5000000, 5000000, 1000000),
    limits = c(-5000000, 5000000),
    labels = c(paste0(seq(5, 0, -1), "M"), paste0(1:5, "M"))
  )  
  theme_minimal()  
  scale_fill_manual(values = my_colors, name = "", labels = c("Female", "Male"))  
  guides(fill = guide_legend(reverse = TRUE))  
  theme(panel.grid.major.x = element_line(linetype = "dotted", size = 0.2, color = "grey40"))  
  theme(panel.grid.major.y = element_blank())  
  theme(panel.grid.minor.y = element_blank())  
  theme(panel.grid.minor.x = element_blank())  
  theme(legend.position = "top")  
  theme(plot.title = element_text(family = my_font, size = 28))  
  theme(plot.subtitle = element_text(family = my_font, size = 13, color = "gray40"))  
  theme(plot.caption = element_text(family = my_font, size = 12, colour = "grey40", face = "italic"))  
  theme(plot.margin = unit(c(1.2, 1.2, 1.2, 1.2), "cm"))  
  theme(axis.text = element_text(size = 13, family = my_font))  
  theme(legend.text = element_text(size = 12, face = "bold", color = "grey30", family = my_font))  
  labs(
    x = NULL, y = NULL,
    title = "Population Pyramids of Vietnam in 2018",
    subtitle = "A population pyramid illustrates the age-sex structure of a country's population and may provide insights about\npolitical and social stability, as well as economic development. Countries with young populations need to\ninvest more in schools, while countries with older populations need to invest more in the health sector.",
    caption = "Data Source: https://www.census.gov"
  )

enter image description here

  • Related