【问题标题】:Insert a .png file inside ggplot with Dates in x-axis在 ggplot 中插入一个 .png 文件,x 轴为日期
【发布时间】:2025-12-18 16:05:02
【问题描述】:

我有下面的数据框:

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))

我想在我的 ggplot 中放一个 .png,例如:

这是我的代码:

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)

我相信我无法显示它,因为 xminxmax 不能接受日期作为输入。

【问题讨论】:

  • 请不要在您的问题中包含library(tidyverse)。有些人不想安装或加载这个巨大的元包。加载实际需要的具体包(本例中没有包)。

标签: r ggplot2 png


【解决方案1】:

我认为我无法显示它,因为 xmin 和 xmax 不能接受日期作为输入。

这是不正确的。你只是没有通过日期。

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"))

【讨论】:

    【解决方案2】:

    要么指定日期as.Date,要么将原始值传递给 xmin 和 xmax。

    # library(tidyverse)
    library(png)
    library(ggplot2)
    mypng <- readPNG('~/Desktop/tt.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 = 350000,ymax= 800000,xmin = 16000,xmax = 17000)
    

    【讨论】: