R语言绘图 | 时序图绘制

本期教程

往期分享教程代码和数据,全部可在社群中获得。

绘图代码

  1. 导入所需R包
library(ggplot2)
library(RColorBrewer)
library(pals)
library(patchwork)
  1. 导入数据
load("./dfplot_dr99.RData")
head(dfplot_dr99)
> head(dfplot_dr99)
       id   yy sd provider             err_est region
7813 hd_1 1900 NA      HYD no error estimation  North
7814 hd_1 1901 NA      HYD no error estimation  North
7815 hd_1 1902 NA      HYD no error estimation  North
7816 hd_1 1903 NA      HYD no error estimation  North
7817 hd_1 1904 NA      HYD no error estimation  North
7818 hd_1 1905 NA      HYD no error estimation  North
load("./df_dr_p99.RData")
head(df_dr_p99)
> head(df_dr_p99)
      id   rr99 provider
1 100057 43.292      HYD
2 100073 48.102      HYD
3 100123 41.100      HYD
4 100180 45.000      HYD
5 100206 46.974      HYD
6 100214 41.290      HYD
  1. 图形设置参数
source(paste0("theme_cool2_V2.r"))

cols<-brewer.set1(9)[c(3,4)]

ylim1 <- c(-12, 16)  
# 设置y轴的显示范围,起点为-12,终点为16

hgt1 <- (ylim1[1] + (abs(ylim1[1]) + abs(ylim1[2])) * 0.02)
# 计算多边形顶部的y轴高度,公式含义如下:
# hgt1 = ymin + 2% * (y轴总高度)
# 即在y轴的底部向上稍微扩展一点,便于可视化展示

df_poly <- data.frame(
  x = c(1981, 2010, 2010, 1981), 
  y = c(ylim1[1], ylim1[1], hgt1, hgt1)
)
# 构建一个四个点的多边形,顶点依次如下:
# x轴从1981到2010,y轴从ylim1[1](即-12)到hgt1(大约-8附近)
# 这个多边形用于在图中以灰色阴影表示“1981–2010年”的区间
  1. 绘制直方图
p1ins<- 
  ggplot()+
  geom_histogram(
    data = df_dr_p99,                 # 使用的数据框是 df_dr_p99
    aes(x = rr99,                     # x轴变量是 rr99,代表降雨量
        fill = provider,              # 按 provider 分组着色
        y = after_stat(density)),     # y轴使用密度(默认是 count,这里转为密度)
    alpha = 0.4,                      # 填色的透明度为0.4(越小越透明)
    position = "identity",           # 图层重叠方式,identity 表示允许不同组图形重叠
    binwidth = 4,                    # 每个直方图箱宽为4单位(mm)
    show.legend = FALSE,             # 不显示图例
    color = NA                       # 不绘制箱体边框
  )+
  scale_x_continuous(
    name = "Rainfall (mm/d)",         # 设置x轴标题
    limits = c(30, 70)                # 限定x轴显示范围在30到70
  )+
  scale_y_continuous(name="Density", breaks=seq(0,0.06,0.03) # y轴刻度为 0.00, 0.03, 0.06
                     )+
  scale_fill_manual(values = cols)+
  theme_cool2_V2()+
  theme(panel.background = element_rect(fill = "transparent",  # panel.background:绘图区背景设置为透明
                                                         colour = NA_character_), 
                         plot.background = element_rect(fill = "transparent",   #plot.background:整个图的背景设置为透明
                                                        colour = NA_character_))
p1ins
  1. 绘制时序图+组图
p1<-
  ggplot()+
  ## 添加置信区间
  stat_summary(
    data = subset(dfplot_dr99),  # 使用数据子集 dfplot_dr99
    geom = "ribbon",  # 绘制带状图(用于表示置信区间)
    aes(x = yy, y = sd * 100, fill = provider),  # x轴为年份,y为标准差×100,颜色分组
    show.legend = FALSE,  # 不显示图例
    fun.data = "mean_cl_boot",  # 使用bootstrapping方法计算平均值和置信区间
    alpha = 0.15,  # 设置带状透明度
    fun.args = list(conf.int = 0.95)  # 设置置信区间为95%
  ) +
  stat_summary(
    data = subset(dfplot_dr99),  # 同上
    size = 1,  # 线条粗细
    geom = "line",  # 绘制线条
    aes(x = yy, y = sd * 100, color = provider),  # 按provider分组设置颜色
    show.legend = FALSE,  # 不显示图例
    fun.y = mean  # 计算每年的平均值
  ) +
  annotate(
    geom = "text",  # 添加文字注释
    label = c("GSA", "HYD"),  # 注释内容
    x = c(1992, 2002),  # 注释x轴位置
    y = c(1, -4),  # 注释y轴位置
    size = 4.5,  # 字体大小
    color = cols,  # 使用 cols 变量中的颜色
    hjust = 1  # 文本右对齐
  ) +
  geom_hline(
    yintercept = 0,  # 添加 y=0 的水平线
    linetype = "dashed",  # 虚线样式
    size = 0.2  # 线条粗细
  ) +
  geom_polygon(
    data = df_poly,  # 使用背景多边形数据
    aes(x = x, y = y),  # x, y坐标
    fill = "grey20",  # 填充颜色为灰色
    alpha = 0.4  # 透明度
  ) +
  annotate(
    geom = "text",  # 添加文字注释
    label = "Daily",  # 注释文字
    x = 1970,  # x轴位置
    y = 14.5,  # y轴位置
    size = 6  # 字体大小
  ) +
  scale_color_manual(name = "", values = cols) +  # 设置线条颜色,去掉图例标题
  scale_fill_manual(name = "", values = cols) +  # 设置带状颜色,去掉图例标题
  scale_x_continuous(
    name = "year",  # 设置x轴名称
    breaks = seq(1900, 2020, 20),  # 设置x轴刻度
    limits = c(1900, 2023)  # 设置x轴显示范围
  ) +
  scale_y_continuous(
    name = "Daily heavy rainfall anomaly (%)",  # y轴标题
    breaks = seq(-24, 24, 4)  # y轴刻度
  ) +
  coord_cartesian(
    xlim = c(1900, 2020),  # 裁剪x轴范围
    ylim = ylim1  # 裁剪y轴范围,ylim1 是预设变量
  ) +
  theme_cool2_V2() +  # 使用自定义主题
  theme(
    plot.title = element_text(face = "bold", size = 18),  # 设置标题加粗及字体大小请你提供具体的代码,以便我为其添加注释进行解释。
    legend.position = c(0.83, 0.2),  # 设置图例位置(比例坐标)
    axis.title.x = element_blank(),  # 去除x轴标题
    axis.text.x = element_text(vjust = -0.5),  # 调整x轴文字位置
    axis.text.y = element_text(margin = margin(r = 70))  # 设置y轴文字右边距
  ) +
  inset_element(
    p1ins,  # 嵌套图对象
    left = 0.015, bottom = 0.58, right = 0.38, top = 0.99  # 设置嵌套图相对主图的位置
  )

版本信息

> sessionInfo()
R version 4.4.0 (2024-04-24 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 22631)

Matrix products: default


locale:
[1] LC_COLLATE=Chinese (Simplified)_China.utf8 
[2] LC_CTYPE=Chinese (Simplified)_China.utf8   
[3] LC_MONETARY=Chinese (Simplified)_China.utf8
[4] LC_NUMERIC=C                               
[5] LC_TIME=Chinese (Simplified)_China.utf8    

time zone: Asia/Shanghai
tzcode source: internal

attached base packages:
[1] grid      stats     graphics  grDevices utils    
[6] datasets  methods   base     

other attached packages:
[1] patchwork_1.3.0    pals_1.10         
[3] RColorBrewer_1.1-3 ggplot2_3.5.1     

loaded via a namespace (and not attached):
 [1] gtable_0.3.6      jsonlite_2.0.0    crayon_1.5.3     
 [4] dplyr_1.1.4       compiler_4.4.0    maps_3.4.2.1     
 [7] promises_1.3.2    tidyselect_1.2.1  Rcpp_1.0.14      
[10] dichromat_2.0-0.1 later_1.4.2       scales_1.3.0     
[13] yaml_2.3.10       fastmap_1.2.0     xiyouAgent_0.0.1 
[16] mime_0.13         R6_2.6.1          labeling_0.4.3   
[19] generics_0.1.3    curl_6.2.2        mapproj_1.2.11   
[22] httr2_1.1.2       htmlwidgets_1.6.4 tibble_3.2.1     
[25] munsell_0.5.1     shiny_1.10.0      pillar_1.10.2    
[28] rlang_1.1.4       httpuv_1.6.16     cli_3.6.3        
[31] withr_3.0.2       magrittr_2.0.3    digest_0.6.37    
[34] rstudioapi_0.17.1 xtable_1.8-4      rappdirs_0.3.3   
[37] lifecycle_1.0.4   vctrs_0.6.5       glue_1.6.2       
[40] farver_2.1.2      colorspace_2.1-1  purrr_1.0.4      
[43] tools_4.4.0       pkgconfig_2.0.3   htmltools_0.5.8.1

**:以上仅代表个人学习笔记,若有错误的部分,请指正!


若我们的教程对你有所帮助,请点赞+收藏+转发,大家的支持是我们更新的动力!!


2024已离你我而去,2025加油!!

2024年推文汇总 (点击后访问)

2023年推文汇总 (点击后访问)

2022年推文汇总 (点击后访问)

往期部分文章

1. 最全WGCNA教程(替换数据即可出全部结果与图形)

推荐大家购买最新的教程,若是已经购买以前WGNCA教程的同学,可以在对应教程留言,即可获得最新的教程。(注:此教程也仅基于自己理解,不仅局限于此,难免有不恰当地方,请结合自己需求,进行改动。)


2. 精美图形绘制教程

3. 转录组分析教程

4. 转录组下游分析

小杜的生信筆記 ,主要发表或收录生物信息学教程,以及基于R分析和可视化(包括数据分析,图形绘制等);分享感兴趣的文献和学习资料!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容