代码之家  ›  专栏  ›  技术社区  ›  PeCaDe

基于R中的条件向绘图添加纹理

  •  1
  • PeCaDe  · 技术社区  · 2 年前

    根据以下内容 dataframe df:

    df <- data.frame(Date=1:5,
                    Cat1=c(1,0,1,0,0),
                    Cat2=c(1,1,1,0,0),
                    Cat3=c(0,1,1,0,1),
                    Cat4=c(0,0,1,1,0),
                    Mask=c(0,1,1,0,0))
    
    df <- tidyr::pivot_longer(df, -1)
    

    平铺图绘制如下:

    ggplot(df%>%filter(name!="Mask"),
           aes(x = Date, y = factor(name, levels = rev(unique(name))), 
               fill = as.factor(value))) +
      geom_tile(color = "black") +
      scale_fill_manual(values = c("white", "grey50")) +
      theme_void() +
      theme(legend.position = "none",
            axis.text = element_text(size = 15),
            axis.title.x = element_text(size = 15),
            plot.margin = margin(20, 20, 20, 20))
    

    具有以下输出:

    enter image description here

    在里面 ggplot ,如何使用列实现纹理 Mask==1 为了填充 Date ?

    enter image description here

    0 回复  |  直到 2 年前
        1
  •  3
  •   PeCaDe    2 年前

    试试(不在CRAN上) ggpattern 包裹

    library(ggplot2)
    #remotes::install_github("coolbutuseless/ggpattern")
    library(ggpattern)
    # set what cells need to be hatched
    df <- df %>%
      mutate(hatch = ifelse(Date %in% c(2,3), "yes", "no"))
      
    ggplot(df%>%filter(name!="Mask"),
           aes(x = Date, y = factor(name, levels = rev(unique(name))), 
               fill = as.factor(value), pattern = hatch)) +
      geom_tile_pattern(pattern_color = "black",
                        pattern_fill = "black",
                        pattern_angle = 45,
                        pattern_density = 0.1,
                        pattern_spacing = 0.025,
                        pattern_key_scale_factor = 0.5) +
      geom_tile(color = "black", alpha = 0.5) +
      scale_pattern_manual(values = c(yes = "stripe", no = "none")) +
      scale_fill_manual(values = c("white", "grey50")) +
      theme_void() +
      theme(legend.position = "none",
            axis.text = element_text(size = 15),
            axis.title.x = element_text(size = 15),
            plot.margin = margin(20, 20, 20, 20))
    

    enter image description here