我该如何将Logo添加到ggplot可视化中?

9

我目前正在制作一个ggplot柱状图,我想在右下角添加一个标志。这是该图表的代码:

df <- data.frame(Names = c("2001", "2004", "2008", "2012", "2018"),
                  Value = c(47053, 68117, 171535, 241214, 234365))

p <- ggplot(df, aes(x = Names, y = Value)) + 
              geom_col(fill = "#DB4D43") + theme_classic() +
              geom_text(aes(label =  Value, y = Value + 0.05), 
                        position = position_dodge(0.9), 
                        vjust = 0)

我按照在网上找到的教程操作,但是无论我在 image_scale 函数中输入什么内容,都不能改变标志的大小,最终标志看起来太小了。
img <- image_read("Logo.png")
img <- image_scale(img,"200")
img <- image_scale(img, "x200")
g <- rasterGrob(img)

size = unit(4, "cm")

heights = unit.c(unit(1, "npc") - size,size)
widths = unit.c(unit(1, "npc") - size, size)
lo = grid.layout(2, 2, widths = widths, heights = heights)

grid.show.layout(lo)

grid.newpage()
pushViewport(viewport(layout = lo))

pushViewport(viewport(layout.pos.row=1:1, layout.pos.col = 1:2))
print(p, newpage=FALSE)
popViewport()

pushViewport(viewport(layout.pos.row=2:2, layout.pos.col = 2:2))
print(grid.draw(g), newpage=FALSE)
popViewport()

g = grid.grab()

grid.newpage()
grid.draw(g)

rm(list=ls())

我找到了另一个教程,试过之后运行时却没有显示任何内容。

mypng <- readPNG('Logo.png')
print(mypng)

logocomp <- p + annotation_raster(mypng, ymin = 4.5,ymax= 5,xmin = 30,xmax = 35)

欢迎来到 Stack Overflow。一个好的建议是添加你正在尝试跟随的教程链接。 - Mark Neal
2个回答

4

您可以使用cowplot包轻松地将图像添加到使用ggplot制作的任何绘图中。我使用R标志作为需要添加到绘图中的图像(使用magick包读取它)。使用cowplot的一个优点是,您可以轻松地指定绘图和图像的大小和位置。

library(cowplot)
library(magick)

img <- image_read("Logo.png")

# Set the canvas where you are going to draw the plot and the image
ggdraw() +
  # Draw the plot in the canvas setting the x and y positions, which go from 0,0
  # (lower left corner) to 1,1 (upper right corner) and set the width and height of
  # the plot. It's advisable that x + width = 1 and y + height = 1, to avoid clipping 
  # the plot
  draw_plot(p,x = 0, y = 0.15, width = 1, height = 0.85) +
  # Draw image in the canvas using the same concept as for the plot. Might need to 
  # play with the x, y, width and height values to obtain the desired result
  draw_image(img,x = 0.85, y = 0.02, width = 0.15, height = 0.15)  

Plot with image


0

试着使用 grid.raster,类似这样:

grid::grid.raster(img, x = 0.15, y = 0.05, width = unit(0.5, 'inches'))

xy用于定义图像的位置。 调整unit()中的数字以调整绘图的大小。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接