Skip to Content

Learning R 教给我的 ggplot2 数据可视化分析

# install needed R packages
remotes::update_packages(c('ggplot2', 'learningr'), upgrade = TRUE)

先做一下准备工作:

library(ggplot2)
data(gonorrhoea, package = 'learningr');

然后就欣赏如何一步一步用图把一个因变量与多个自变量之间的关系展示清楚:

ggplot(gonorrhoea, aes(Age.Group, Rate)) + 
    geom_bar(stat = "identity") + 
    facet_wrap(~Year + Ethnicity + Gender)

ggplot(gonorrhoea, aes(Age.Group, Rate, group = Year, fill = Year)) + 
    geom_bar(stat = "identity", position = 'dodge') + 
    facet_wrap(~Ethnicity + Gender)

ggplot(gonorrhoea, aes(Age.Group, Rate, group = Year, color = Year)) + 
    geom_line() + 
    facet_wrap(~Ethnicity + Gender)

ggplot(gonorrhoea, aes(Age.Group, Rate, group = Year, color = Year)) + 
    geom_line() + 
    facet_grid(Ethnicity~Gender)

ggplot(gonorrhoea, aes(Age.Group, Rate, group = Year, color = Year)) + 
    geom_line() + 
    facet_grid(Ethnicity~Gender, scales  =  "free_y")