美文网首页R plot
ggplot2可视化经典案例(3)之散点图

ggplot2可视化经典案例(3)之散点图

作者: R语言数据分析指南 | 来源:发表于2021-02-03 22:53 被阅读0次

通过简单的代码,将一个简简单单的散点图绘制的更加优雅,喜欢的小伙伴可以关注个人公众号R语言数据分析指南持续分享更多优质案例,在此先行拜谢了!!

加载R包

library(tidyverse)
library(colorspace)
library(ggtext)
library(tidytuesdayR)
library(ggdist)

数据清洗

通过tidytuesdayR包可以轻松的访问每周的TidyTuesday项目数据集

pal <- c("#FF8C00","#A034F0", "#159090")

tuesdata <- tidytuesdayR::tt_load('2020-07-28') 

df_penguins <- tuesdata$penguins

df_peng_summary <- tribble(~species, ~x, ~y,
"Adelie", 34.7, 20.7,"Chinstrap",55.7,19,
"Gentoo",50.7,13.6) %>% 
  full_join(df_penguins %>% group_by(species) %>% 
      summarize(across(contains("_"),
list(median = ~median(.x, na.rm = T),
sd = ~sd(.x, na.rm = T)))))

数据可视化

首先根据数据画出误差线

p <- ggplot(df_penguins,aes(bill_length_mm,bill_depth_mm)) +
geom_errorbar(data = df_peng_summary,
aes(x = bill_length_mm_median,
ymin = bill_depth_mm_median - bill_depth_mm_sd,
ymax = bill_depth_mm_median + bill_depth_mm_sd,
color = species,
color = after_scale(darken(color, .2))),
inherit.aes = F,width = .8,size = .8)+
geom_errorbar(data = df_peng_summary,
aes(y = bill_depth_mm_median,
xmin = bill_length_mm_median - bill_length_mm_sd,
xmax = bill_length_mm_median + bill_length_mm_sd,
color = species, 
color = after_scale(darken(color, .2))),
inherit.aes = F,width = .5,size = .8)

添加数据点

此处添加2个geom_point(),我们通过一个点向另一个点上添加边框,并设置填充颜色为透明

p + geom_point(aes(fill = species,
size = body_mass_g), 
shape = 21,color = "transparent",alpha = .3)+
geom_point(aes(size = body_mass_g),shape = 21,
color = "white",
fill = "transparent")+guides(size=FALSE)+
geom_text(data = df_peng_summary,
            aes(x = x, y = y,label = species,color = species),
            size = 5.6)+
  scale_x_continuous(limits = c(30, 60),breaks = seq(30, 60, by = 5),
                     expand = c(0, 0))+
  scale_y_continuous(limits = c(12, 22),breaks = seq(12, 22, by = 2),
                     expand = c(0, 0))+
  scale_color_manual(values = pal,guide = F)+
  scale_fill_manual(values = pal,guide = F)+
  xlab(NULL)+ylab(NULL)+
  theme(axis.text.x=element_blank(),
        axis.text.y=element_blank())

scale_*_manual设置线条与点的颜色一致

原文链接:https://mp.weixin.qq.com/s/ttrDTidbkFduK_mhTmV7Eg

相关文章

网友评论

    本文标题:ggplot2可视化经典案例(3)之散点图

    本文链接:https://www.haomeiwen.com/subject/mehvtltx.html