Search code examples
rggplot2png

Insert a .png file inside ggplot with Dates in x-axis


I have the dataframe below:

d1_7<-structure(list(conm = c("Facebook Inc", "Facebook Inc", "Facebook Inc", 
"Facebook Inc", "Facebook Inc", "Facebook Inc", "Facebook Inc", 
"Facebook Inc", "Facebook Inc", "Facebook Inc", "Facebook Inc", 
"Facebook Inc", "Facebook Inc", "Facebook Inc", "Facebook Inc", 
"Facebook Inc", "Facebook Inc", "Facebook Inc", "Facebook Inc", 
"Facebook Inc", "Facebook Inc", "Facebook Inc"), datadate = structure(c(14974, 
14974, 15339, 15339, 15705, 15705, 16070, 16070, 16435, 16435, 
16800, 16800, 17166, 17166, 17531, 17531, 17896, 17896, 18261, 
18261, 18627, 18627), label = "Data Date", format.stata = "%td", class = "Date"), 
    fin_var = c("mkt_val", "sale", "mkt_val", "sale", "mkt_val", 
    "sale", "mkt_val", "sale", "mkt_val", "sale", "mkt_val", 
    "sale", "mkt_val", "sale", "mkt_val", "sale", "mkt_val", 
    "sale", "mkt_val", "sale", "mkt_val", "sale"), fin_value = c(NA, 
    1974, NA, 3711, 60321.3848471, 5089, 132250.58, 7872, 203944.28, 
    12466, 293361.98, 17928, 329388.15, 27638, 511910.46, 40653, 
    378850.1, 55838, 585783.5, 70697, 778779.16, 85965)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -22L))

and I want to put a .png inside my ggplot like:

Here is my code:

library(tidyverse)
library(png)
library(ggplot2)
mypng <- readPNG('C:/Users/User/Documents/Avilla ggplot/mark-zuckerberg-celebrity-mask.png')


plot <- ggplot(d1_7, aes(x = datadate, y = fin_value)) +
  geom_col(aes(fill = conm))+
  facet_wrap(~conm,ncol=1)+
  theme_minimal()+
  theme(legend.position = "none")+
  ylab('Profits in $ million')+
  xlab('Fiscal Year')+
  scale_fill_manual(values=c("#5cc9f5"))
plot+ guides(fill=guide_legend(title=""))+annotation_raster(mypng, ymin = 500000,ymax= 600000,xmin = 2014,xmax = 2015)

I believe that I cannot display it because xmin and xmax cannot accept dates as inputs. enter image description here


Solution

  • I believe that I cannot display it because xmin and xmax cannot accept dates as inputs.

    That's incorrect. You just don't pass dates.

    plot+ guides(fill=guide_legend(title=""))+
      annotation_raster(mypng, ymin = 500000,ymax= 600000,
                        xmin = as.Date("2014-01-01"),xmax = as.Date("2015-01-01"))
    

    resulting plot