Skip to content

Instantly share code, notes, and snippets.

@SPLOpenData
Last active March 22, 2021 23:39
Show Gist options
  • Save SPLOpenData/334bd6dcc69da22551b79235610d815d to your computer and use it in GitHub Desktop.
Save SPLOpenData/334bd6dcc69da22551b79235610d815d to your computer and use it in GitHub Desktop.
#This R script demonstrates use of the library ggpattern to add image textures to visualizations + magick to edit image files.
#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 svg images to use as textures. Edit in 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)
img_paths<-c(n_cake_img, list.files(pattern = 'water.png',full.names=TRUE))
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 labels
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))
)
@SPLOpenData
Copy link
Author

cake

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment