美文网首页
ggplot2优雅的添加图表

ggplot2优雅的添加图表

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

本节介绍如何在{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)

相关文章

  • ggplot2优雅的添加图表

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

  • R语言宏基因组学统计分析(第四章)笔记之ggplot2

    4.3 ggplot2简介 4.3.1 ggplot2和图形语法 ggplot2可以用来创建优雅的图形,由于它的...

  • ggplot2优雅的给图象添加图标

    本节来解释如何使用rphylopic包给图像添加各种动植物图,rphylopic是一个公开的图像数据库可以免费使用...

  • 动态图标&

    动态图表 一、双坐标图表 选中区域--插入--推荐图表--所以图表--组合图--同比--添加数据标签--美化...

  • 今日课程:动态图表

    一、双坐标图表 选中区域--插入--推荐图表--所以图表--组合图--同比--添加数据标签--美化 二、动态图表 ...

  • R | 一探ggplot2

    在R语言的可视化工具中,ggplot2无疑是一款简洁、强大、优雅的工具。长话短说,我们直接进入ggplot2的代码...

  • 认识图表

    1.双坐标图表 选中数据区域 插入 推荐的图表 所有图表 组合图 同比 添加数据标签 2.动态图表 a.特点 “活...

  • ali F2(移动端数据展示) 入门

    F2 安装 基本使用 Chart 创建图表实例 Chart.source 添加数据 声明图表类型 图表类型poin...

  • R for data science (第一章) ②

    使用ggplot2进行数据可视化①使用ggplot2进行数据可视化② 添加其他变量的一种方法是aesthetics...

  • 9 可视化数据探索 R作图ggplot

    ggplot2 探索数据 做成合并的图 最终效果 添加注释 https://www.shixiangwang.to...

网友评论

      本文标题:ggplot2优雅的添加图表

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