百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

R 数据可视化——ggplot 色块图 r软件ggplot

bigegpt 2024-09-27 00:35 3 浏览

前言

绘制色块图的函数有三个,其中 geom_rect()geom_tile() 除了参数不同之外,其他都是一样的。

  • geom_rect 使用四个角参数:xmin, xmax, ymin and ymax
  • geom_tile 指定了中心位置和大小参数:x, y, width, height

geom_raster 是条块大小相同时 geom_tile 的快速版本,而且当输出为 PDF 时所占空间也更小

示例

绘制简单的热图

ggplot(faithfuld, aes(waiting, eruptions)) +
 geom_raster(aes(fill = density))

增加图像的平滑度

ggplot(faithfuld, aes(waiting, eruptions)) +
 geom_raster(aes(fill = density), interpolate = TRUE)

如果想要绘制矩形块,可以使用 geom_tile()

df <- data.frame(
  x = rep(c(2, 5, 7, 9, 12), 2),
  y = rep(c(1, 2), each = 5),
  z = factor(rep(1:5, each = 2)),
  w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2)
)
ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = z), colour = "grey50")
ggplot(df, aes(x, y, width = w)) +
  geom_tile(aes(fill = z), colour = "grey50")

geom_rect()

ggplot(df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = y, ymax = y + 1)) +
  geom_rect(aes(fill = z), colour = "grey50")

极坐标化

p1 <- ggplot(df, aes(x, y, width = w)) +
  geom_tile(aes(fill = z), colour = "grey50") +
  coord_polar(theta = 'x')

p2 <- ggplot(df, aes(x, y, width = w)) +
  geom_tile(aes(fill = z), colour = "grey50") +
  coord_polar(theta = 'y')

plot_grid(p1, p2)

样式

1. 华夫饼图

华夫饼图包括两种类型:

  1. 块状华夫饼图:

用于展示每组数据占总体的比例情况,可以快速看出数据中不同类别的分布以及占比,同时也可以知道不同分组之间的分布差异

其中堆积型侧重于展示类别数值

df <- tibble(
  x = rep(1:10, 10),
  y = rep(1:10, each=10),
  class = sort(sample(mpg$class, 100))
)

sample_n(df, 67) %>% 
  arrange(x, y) %>% 
  group_by(x) %>% 
  mutate(y = 1:n()) %>%
  ggplot(aes(x, y, fill = class)) +
  geom_tile(colour = "white") +
  # geom_point(size = 12, shape = 21) +
  coord_fixed() +
  theme(panel.background = element_blank(),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank())

以及侧重于展示类别占比的百分比堆积型

ggplot(df, aes(x, y, fill = class)) +
  geom_tile(colour = "white") +
  scale_y_continuous(trans = "reverse") +
  theme(panel.background = element_blank(),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank())
  1. 点状华夫饼图:

以点图矩阵的方式展示离散数据,用颜色来区分不同组别。功能与块状华夫饼图相同

ggplot(df, aes(x, y, fill = class)) +
  # geom_tile(colour = "white") +
  geom_point(size = 12, shape = 21) +
  coord_fixed() +
  scale_y_continuous(trans = "reverse") +
  theme(panel.background = element_blank())

2. 马赛克图

马赛克图用于显示分类数据中一对变量之间的关系。

df <- tibble(
  gene = rep(LETTERS[1:5], 4),
  status = rep(c("alpha", "beta", "gamma", "delta"), each = 5),
  value = sample(1:100, 20),
  percent = rep(c(10, 30, 30, 20, 10), 4)
)

df %>% 
  group_by(status) %>%
  mutate(xmax = cumsum(percent), xmin = xmax - percent) %>%
  group_by(gene) %>% 
  mutate(ytmp = value * 100 / sum(value), ymax = cumsum(ytmp), ymin = ymax - ytmp) %>%
  mutate(x = (xmin + xmax) / 2, y = (ymin + ymax) / 2) %>%
  ggplot() + 
  geom_rect(aes(xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax, fill = status),
            colour = "black") +
  geom_text(aes(x, y, label = paste0(round(ytmp, 2), "%"))) +
  geom_text(aes(x = x, y = 103, label = gene)) +
  theme(panel.background = element_blank())

马赛克图

3. 瀑布图

假设我们有如下突变数据

> data
# A tibble: 2,432 x 3
   sample   gene  MutFunc          
   <chr>    <chr> <chr>            
 1 C1803704 ATM   nonsynonymous SNV
 2 C1803704 BRAF  nonsynonymous SNV
 3 C1803704 BRCA1 synonymous SNV   
 4 C1803704 BRCA1 nonsynonymous SNV
 5 C1803704 BRCA2 nonsynonymous SNV
 6 C1803704 BRCA2 synonymous SNV   
 7 C1803704 BRCA2 stopgain         
 8 C1803704 BRD4  nonsynonymous SNV
 9 C1803704 EOMES nonsynonymous SNV
10 C1803704 EPCAM nonsynonymous SNV
# … with 2,422 more rows

我们需要绘制基因在样本中的突变情况和每个样本的突变基因数情况,以及每个基因在样本中的突变情况,三个图结合在一起。

颜色表示不同的突变类型。

首先,对数据进行处理,

data <- df %>% select(sample, gene, MutFunc) %>%
  distinct() %>%
  filter(MutFunc != ".")

genes <- count(data, gene) %>%
  top_n(n = 20, wt = n) %>%
  mutate(percent = round(n * 100 / sum(n), 1)) %>%
  arrange(desc(n))
  
samples <- subset(data, gene %in% genes$gene) %>%
  count(sample) %>% arrange(desc(n)) %>%
  rename(num = n)

df <- inner_join(data, genes) %>%
  mutate(gene = factor(gene, levels = rev(genes$gene)),
         sample = factor(sample, levels = samples$sample)) %>%
  inner_join(samples)

转换为这个格式的数据

> df
# A tibble: 978 x 6
   sample   gene   MutFunc               n percent   num
   <chr>    <fct>  <chr>             <int>   <dbl> <int>
 1 C1803704 ATM    nonsynonymous SNV    16     1.6    16
 2 C1803704 BRCA1  synonymous SNV      137    14      16
 3 C1803704 BRCA1  nonsynonymous SNV   137    14      16
 4 C1803704 BRCA2  nonsynonymous SNV   274    28      16
 5 C1803704 BRCA2  synonymous SNV      274    28      16
 6 C1803704 BRCA2  stopgain            274    28      16
 7 C1803704 EOMES  nonsynonymous SNV    31     3.2    16
 8 C1803704 PIK3CA nonsynonymous SNV    39     4      16
 9 C1803704 TP53   stopgain             55     5.6    16
10 C1803710 BRCA1  synonymous SNV      137    14      11
# … with 968 more rows

然后绘制这三张图

p1 <- ggplot(df) +
  geom_tile(aes(x = sample, y = gene, fill = MutFunc)) +
  # geom_text(aes(x = -4, y = gene, label = percent), data = genes) +
  # 图例行数的调整放到 fill,单独用 guides 无效
  scale_fill_discrete(guide = guide_legend(nrow = 3)) +
  scale_y_discrete(position = "right") +
  theme(axis.text.x = element_blank(),
        axis.text.y.left = element_text(size = 4),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        legend.position = "bottom",
        legend.background = element_rect(fill = 'white', colour = 'black')
        )
# 样本的突变基因数目条形图
p2 <- ggplot(df) +
  geom_bar(aes(x = sample, fill = MutFunc)) +
  # 使用 expand 删除数据与轴之间的空隙
  scale_y_continuous(breaks = seq(0, 25, 5), limits = c(0, 25), 
                     expand = expansion(mult = 0, add = 0)) +
  theme(
    legend.position = "none",
    panel.background = element_blank(),
    axis.title = element_blank(),
    axis.ticks.x = element_blank(),
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.length.y.left = unit(.25, "cm"),
    axis.line.y.left = element_line(colour = "black"),
  )
# 突变基因的突变频数条形图
p3 <- ggplot(df) +
  geom_bar(aes(y = gene, fill = MutFunc)) +
  scale_x_continuous(position = "top", breaks = seq(0, 280, 70),
                     limits = c(0, 280),
                     expand = expansion(mult = 0, add = 0)) +
  theme(
    legend.position = "none",
    panel.background = element_blank(),
    axis.title = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.length.x.top = unit(.25, "cm"),
    axis.line.x.top = element_line(colour = "black")
  )

最后将三张图拼接起来

p12 <- plot_grid(p2, p1, nrow = 2, align = "v",
          rel_heights = c(1, 5))

pr <- plot_grid(NULL, p3, NULL, nrow = 3, align = "v",
                rel_heights = c(0.95, 5, 1.05))

plot_grid(p12, pr, ncol = 2, align = "h",
          rel_widths = c(5, 1))

瀑布图

代码:https://github.com/dxsbiocc/learn/tree/main/R/plot/color_block.R

相关推荐

有些人能留在你的心里,但不能留在你生活里。

有时候,你必须要明白,有些人能留在你的心里,但不能留在你生活里。Sometimes,youhavetorealize,Somepeoplecanstayinyourheart,...

Python学不会来打我(34)python函数爬取百度图片_附源码

随着人工智能和大数据的发展,图像数据的获取变得越来越重要。作为Python初学者,掌握如何从网页中抓取图片并保存到本地是一项非常实用的技能。本文将手把手教你使用Python函数编写一个简单的百度图片...

软网推荐:图像变变变 一“软”见分晓

当我们仅需要改变一些图片的分辨率、裁减尺寸、添加水印、标注文本、更改图片颜色,或将一种图片转换为另一种格式时,总比较讨厌使用一些大型的图像处理软件,尤其是当尚未安装此类软件时,更是如此。实际上,只需一...

首款WP8.1图片搜索应用,搜照片得资料

首款WP8.1图片搜索应用,搜照片得资料出处:IT之家原创(天际)2014-11-1114:32:15评论WP之家报道,《反向图片搜索》(ReverseImageSearch)是Window...

分享一组美图(图片来自头条)(头条美女头像)

...

盗墓笔记电视剧精美海报 盗墓笔记电视剧全集高清种子下载

出身“老九门”世家的吴邪,因身为考古学家的父母在某次保护国家文物行动时被国外盗墓团伙杀害,吴家为保护吴邪安全将他送去德国读书,因而吴邪对“考古”事业有着与生俱来的兴趣。在一次护宝过程中他偶然获得一张...

微软调整Win11 24H2装机策略:6月起36款预装应用改为完整版

IT之家7月16日消息,微软公司今天(7月16日)发布公告,表示自今年6月更新开始,已默认更新Windows1124H2和WindowsServer2025系统中预装...

谷歌手把手教你成为谣言终结者 | 域外

刺猬公社出品,必属原创,严禁转载。合作事宜,请联系微信号:yunlugongby贾宸琰编译、整理11月23日,由谷歌新闻实验室(GoogleNewsLab)联合Bellingcat、DigD...

NAS 部署网盘资源搜索神器:全网资源一键搜,免费看剧听歌超爽!

还在为找不到想看的电影、电视剧、音乐而烦恼?还在各个网盘之间来回切换,浪费大量时间?今天就教你如何在NAS上部署aipan-netdisk-search,一款强大的网盘资源搜索神器,让你全网资源...

使用 Docker Compose 简化 INFINI Console 与 Easysearch 环境搭建

前言回顾在上一篇文章《搭建持久化的INFINIConsole与Easysearch容器环境》中,我们详细介绍了如何使用基础的dockerrun命令,手动启动和配置INFINICon...

为庆祝杜特尔特到访,这个国家宣布全国放假?

(观察者网讯)近日,一篇流传甚广的脸书推文称,为庆祝杜特尔特去年访问印度,印度宣布全国放假,并举办了街头集会以示欢迎。菲媒对此做出澄清,这则消息其实是“假新闻”。据《菲律宾世界日报》2日报道,该贴子...

一课译词:毛骨悚然(毛骨悚然的意思是?)

PhotobyMoosePhotosfromPexels“毛骨悚然”,汉语成语,意思是毛发竖起,脊梁骨发冷;形容恐惧惊骇的样子(withone'shairstandingonend...

Bing Overtakes Google in China&#39;s PC Search Market, Fueled by AI and Microsoft Ecosystem

ScreenshotofBingChinahomepageTMTPOST--Inastunningturnintheglobalsearchenginerace,Mic...

找图不求人!6个以图搜图的识图网站推荐

【本文由小黑盒作者@crystalz于03月08日发布,转载请标明出处!】前言以图搜图,专业说法叫“反向图片搜索引擎”,是专门用来搜索相似图片、原始图片或图片来源的方法。常用来寻找现有图片的原始发布出...

浏览器功能和“油管”有什么关联?为什么要下载

现在有没有一款插件可以实现全部的功能,同时占用又小呢,主题主要是网站的一个外观,而且插件则主要是实现wordpress网站的一些功能,它不仅仅可以定制网站的外观,还可以实现很多插件的功能,搭载chro...