What R function can I use to use a image link as a background image in a ggplot2 bar graph?

点点圈 提交于 2020-04-16 02:32:13

问题


I've been trying to create a simple program that would create a bar graph based on album lengths, with the album's cover as the background to the image. However, I cannot figure out how to turn Spotify's image link into a background image that ggplot2 can parse into a background. Spotify's get_album() simply comes with a link to an image (ex:"

https://i.scdn.co/image/ab67616d0000b273922a12ba0b5a66f034dc9959

"). How could I turn this into a displayable image in a ggplot2 bar graph like so:

ggplot(data=album_df, aes(x=rev(factor(track_names, track_names)), y=-1 * track_length)) +
  ggtitle("Songs vs length")+
    annotation_custom(rasterGrob(album_cover, 
                               width = unit(1,"npc"), 
                               height = unit(1,"npc")), 
                               -Inf, Inf, -Inf, Inf)+
  geom_bar(stat="identity", position = "identity", color = 'NA', alpha = 0.9, width = 1, fill = 'white') +
    scale_y_continuous(expand = c(0, 0), limits = c(-1 * max_track, 0)) +
    scale_x_discrete(expand = c(0, 0)) +
  theme(axis.title.x=element_blank(), 
        axis.title.y=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()
        ) + 
   coord_flip() 

the annotation_custom is where I have currently stored the background image using a read as jpeg format, however this requires I first download the image, which I cannot do if I expect this to be a public website.


回答1:


I don't fully understand what you are referring to when saying that you cannot download the image 'if you expect it to be a public website'. If you are referring to licensing issues, I guess any un-licensed use of the image would be of concern.

Here is a solution which downloads the image from the link to a temporary file which you can then delete if you want (note you still have the image stored as an object, and - more importantly - you are still going to use it).

I am using the picture of your avatar, which is in png format. For the Spotify jpeg image, use jpeg::readJPEG() instead.

I am using ggpubr::background_image because this makes this way easier than annotate_custom

library(ggplot2)

download.file('https://www.gravatar.com/avatar/e01b978970939af0a188df8c28136a67?s=328&d=identicon&r=PG&f=1',
              destfile= 'tmp.png')                     
img <- png::readPNG('tmp.png')

# Plot with background image
ggplot(iris, aes(Species, Sepal.Length)) +
  ggpubr::background_image(img)

Created on 2020-03-19 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/60752269/what-r-function-can-i-use-to-use-a-image-link-as-a-background-image-in-a-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!