R语言做图绘图技巧做图

R优雅的绘制三元相图

2021-07-18  本文已影响0人  R语言数据分析指南

本节来介绍如何通过Ternary绘制3元相图

加载R包

install.packages('Ternary')
library(tidyverse)
library(Ternary)

加载数据

scooby <- read_csv('scoobydoo.csv')

数据清洗

数据清洗部分请参考tidyverse数据处理教程汇总这篇文档

df <- scooby %>%
  select(index, starts_with("unmask_"), ends_with("_amount")) %>%
  select(-unmask_other) %>%
  pivot_longer(cols = starts_with("unmask_"),
    names_to = "who_unmasked",
    values_to = "tmp",
    names_prefix = "unmask_") %>%
  filter(tmp != "FALSE") %>%
  select(-tmp) %>%
  group_by(who_unmasked) %>%
  summarise(
    monsters = sum(monster_amount),
    suspects = sum(suspects_amount),
    culprits = sum(culprit_amount)
  ) %>% janitor::adorn_percentages(denominator = "col") %>%
  select(monsters, suspects, culprits, who_unmasked) %>%
  add_column(color = cbPalette8[c(1, 7, 4, 6, 3)]) %>%
  mutate(who_unmasked = str_to_title(who_unmasked))
triangle <- matrix(c(50,50,0,50,0,
                     50,0,50,50),ncol=3,byrow = TRUE)

创建画布

TernaryPlot函数会创建一个空白图

TernaryPlot(
  alab = "A \u2192",
  blab = "B \u2192",
  clab = "\u2190 C",
  lab.cex = 1.5,
  col = "#FFFFFF",
  grid.lines = 10,
  grid.col = "#DDDDDD",
  grid.lty = "solid",
  grid.lwd = 1,
  grid.minor.lines = 4,
  grid.minor.col = "#EEEEEE",
  grid.minor.lty = "solid",
  grid.minor.lwd = 1)

添加线条

TernaryPolygon(triangle, border = 'green')
TernaryLines(list(c(0, 50, 0), c(50, 0, 50)), lty = 2, col = "red")
TernaryLines(list(c(0, 0, 50), c(50, 50, 0)), lty = 2, col = "blue")
TernaryLines(list(c(50, 0, 0), c(0, 50, 50)), lty = 2, col = "yellow")

添加点&文本

TernaryPoints(df[1:3], col = df$color, pch = 16, cex = 1.5)
TernaryText(df[,1:3],
            labels = df$who_unmasked,
            col = df$color, pos = 4,cex =1)

喜欢的小伙伴欢迎关注我的公众号

R语言数据分析指南,持续分享数据可视化的经典案例及一些生信知识,希望对大家有所帮助

上一篇 下一篇

猜你喜欢

热点阅读