ggplot2优雅的添加图表

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

本节介绍如何在{ggplot2} 图中插入文本表格,就像在指定位置插入文本标签一样

加载R包

library(ggpp)
library(tidyverse)
library(tibble)

构建图表

mtcars %>%
  group_by(cyl) %>%
  summarize(wt = mean(wt), mpg = mean(mpg)) %>%
  ungroup() %>%
  mutate(wt = sprintf("%.2f", wt),
         mpg = sprintf("%.1f", mpg)) -> tb

df <- tibble(x = 5.45, y = 34, tb = list(tb))
# A tibble: 3 x 3
    cyl wt    mpg  
  <dbl> <chr> <chr>
1     4 2.29  26.7 
2     6 3.12  19.7 
3     8 4.00  15.1 

插入图表

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
  geom_point() +
  geom_table(data = df, aes(x = x, y = y, label = tb))
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
  geom_point() +
  geom_table(data = df, aes(x = x, y = y, label = tb),
             table.rownames = TRUE, table.theme = ttheme_gtstripes)
ggplot(mtcars,aes(wt, mpg, colour = factor(cyl))) +
  geom_point() +
  geom_table(data = df, aes(x = x, y = y, label = tb),
             table.theme = ttheme_gtminimal) +
  theme_classic()

插入图片

p <- ggplot(mtcars, aes(factor(cyl), mpg, colour = factor(cyl))) +
  stat_boxplot() +
  labs(y = NULL, x = "Engine cylinders (number)") +
  theme_bw(9) + theme(legend.position = "none")

data.tb <- mtcars %>%
  group_by(cyl) %>%
  summarise(wt = mean(wt), mpg = mean(mpg))
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
  geom_x_margin_arrow(data = data.tb,
                      aes(xintercept = wt, color = factor(cyl)),
                      arrow.length = 0.05) +
  geom_y_margin_arrow(data = data.tb,
                      aes(yintercept = mpg, color = factor(cyl)),
                      arrow.length = 0.05) +
  annotate("plot_npc", npcx = "right", npcy = "top", 
           label = p + theme(axis.title.y = element_blank())) +
  expand_limits(y = 10) +
  geom_point(show.legend = FALSE)
上一篇下一篇

猜你喜欢

热点阅读