首页 > 解决方案 > 使用 ggpattern 使用图像创建条形图

问题描述

我想创建一个 ggplot 条形图,使用我自己的照片来填充条形。我试过使用 ggpattern 来做到这一点,但是我遇到了麻烦。将所选 .jpeg 照片加载到 R 中的最佳方法是什么,它们应该如何合并到条形图中?

标签: rggplot2bar-chart

解决方案


ggpattern是一个不错的选择,但您也可以使用ggtextures. 如果由于某种原因,您的图像文件无法与任一库一起使用,请尝试将图像转换为另一种格式。如果您想完全保留在 R 中,请使用magick库转换您的文件。

由于您没有提供示例数据,因此我添加了一个可以运行的随机示例。我magick用来加载和裁剪图像,然后在本地保存为 PNG 图像。然后将 aggpattern::geom_col_pattern()添加到 aggplot()中以用图像填充条形图。ggppattern "geoms" 中的参数是高度可配置的。

 #This R script demonstrates use of the library ggpattern to add image textures to visualizations + magick to edit image files
    library(ggpattern) #remotes::install_github("coolbutuseless/ggpattern")
    library(ggplot2)
    library(magick)
    library(tibble)
    library(dplyr)
    #create data to visualize
    cakes<-tibble( cake_name=c("Chocolate Cake","Cream Cake ","Pound Cake",
                        "White or Yellow Cake","Devil’s Food Cake",
                        "Sponge Cake","Angel Food Cake","Water"),
            gravity = c(.9,.85,.8,.7,.7,.5,.3,1)) %>%
            dplyr::arrange(-.$gravity)
    #Get images to use as textures. Edit using magick library
    cake_img<-magick::image_read_svg(c("https://upload.wikimedia.org/wikipedia/commons/4/49/Cartoon_Happy_Birthday_Cake.svg"))%>%
      magick::image_rotate(., 90) %>%image_crop(., "725x600+50+75")
    water_img<-image_read_svg('https://upload.wikimedia.org/wikipedia/commons/0/06/Water_compartment.svg') %>%image_crop(., "500x250+150")
    #save edited images locally
    magick::image_write(cake_img, path = "cake.png", format = "png")
    magick::image_write(water_img, path = "water.png", format = "png")
    #Create a vector of filepaths to the images that will be used
    n_cake_img<-list.files(pattern = 'cake.png',full.names=TRUE) %>% rep(.,nrow(cakes)-1)
#The vector of image paths is same length as data to be visualized.
img_paths<-c(n_cake_img, list.files(pattern = 'water.png',full.names=TRUE))
    
    #plot the data with images as background.           
    p <- ggplot(cakes)+ 
      geom_col_pattern( aes(reorder(cake_name,gravity), 
                            gravity, pattern_filename =reorder(cake_name,gravity)),
        pattern = 'image',
        pattern_fill="white",
        fill="white",
        pattern_type = 'expand',
        pattern_aspect_ratio = 1) +
         theme_bw(18) +
      xlab("", size=12)+
      theme(legend.position = 'none') +
      scale_pattern_filename_discrete(choices = img_paths)+
      coord_flip()
    #add labeling
    p +
      labs(title = "Optimal Specific Gravity of Cake Batters",
           subtitle = "Ratio of batter weight & room temperature water of the same volume.",
           caption = "Data source: https://bakerpedia.com/processes/specific-gravity-cakes/
    Image credit(s): https://commons.wikimedia.org/wiki/File:Water_compartment.svg
    https://upload.wikimedia.org/wikipedia/commons/4/49/Cartoon_Happy_Birthday_Cake.svg")+
      theme(
      plot.title = element_text(color = "Black", size = 32, face = "bold"),
      plot.subtitle = element_text(color = "darkgrey", size = 14),
      plot.caption = element_text(color = "grey",size = 11, face = "italic"),
      axis.title.x = element_text(size = 20),
      axis.text.y=element_text(size=rel(1.5))
    )

显示蛋糕比重的 ggpattern 可视化示例

如您所见,ggpattern::geom_col_pattern()仅引用图像文件路径,因此您不会在绘图之前将图像真正加载为 R 对象。

magick这是在有用的情况下转换库中图像文件的简化示例。

your_img<-magick::image_read("yourfile.jpeg")
your_new_img<-magick::image_write(your_img, path = "newfile.png", format = "png")

推荐阅读