Reputation: 2526
I'm trying to overlay a png file over my barplot, so I can eventually fill the image with just my data. However, when I overlay the png, it completely covers my data. I only want the black lines of the image to be retained, not the portion that should be invisible.
How do I fix this issue?
library(png)
library(dplyr)
library(ggplot2)
#Sample data
test_data <- tibble(percent = c(20, 30, 10, 15, 25),
reason = c("Projects", "Coworkers", "Other", "Growth", "Benefits"),
year = c("2021"))
#read in heart png--see description for link to where I got it, but feel free to use any png
img <- readPNG("/home/mydesktop/Data Viz/heart.png")
#Code
ggplot(test_data, aes(x = year, y = percent, fill = reason)) +
geom_bar(stat = "identity") +
annotation_raster(img, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)
Here's what the output looks like:
Here's where I got the heart from, but as I said in the code, feel free to use any png. For the solution, I want the heart to be on top of the bars (and it's ok if it goes beyond the bars).
Upvotes: 0
Views: 161
Reputation: 41225
If you have an image without background, you can use this code:
library(grid)
library(png)
img <- readPNG("~/Downloads/Heart-removebg-preview.png")
#Sample data
test_data <- tibble(percent = c(20, 30, 10, 15, 25),
reason = c("Projects", "Coworkers", "Other", "Growth", "Benefits"),
year = c("2021"))
#Code
ggplot(test_data, aes(x = year, y = percent, fill = reason)) +
geom_bar(stat = "identity") +
annotation_raster(img, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)
With output:
I used this image:
Upvotes: 0
Reputation: 173793
You have simply downloaded the wrong file from the website. You don't have a transparent png. You can tell this because of the checkerboard behind the loveheart - this would not be displayed in ggplot if you had a transparent image. It seems you have probably just clicked on the image displayed on the page and done a "save as", but you need to go to the download button on the right near the bottom of the page (which is difficult to find). If you do this, save the file, and re-run your code, you will get:
Upvotes: 1