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:
CodePudding user response:
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: