如何解决在 r 中向背景图像添加半透明层时出现错误:无效输入:date_trans 仅适用于 Date 类对象
我正在尝试在 r 图中向 背景图像 添加 半透明覆盖黑色层。它通过使用 annotate
工作并从以下位置获得解决方案:How to add a black overlay semi transparent layer above the background image in r?
问题:半透明层没有完全从左到右延伸在绘图图像上。
如果我尝试使用 xmin = -Inf,xmax = Inf
那么它会由于日期刻度 xaxis 而出现错误。
那么如何用图层覆盖整个图像?
df
library(tidyverse)
library(lubridate)
library(ggpubr)
library(grid)
library(jpeg)
file_url1 <- "https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/ts_all_long4.csv"
ts_all_long <- read.csv(url(file_url1))
ts_all_long <- ts_all_long %>%
mutate(date = as.Date(date))
ts_all_long %>%
filter(Country.Region == "Brazil") %>%
ggplot(aes(x = date,y = Confirmed_daily)) +
background_image(readJPEG("/home/johannes/Downloads/coronavirus-4972480_1920.jpg")) +
annotate("rect",xmin = min(ts_all_long$date),xmax = max(ts_all_long$date),ymin = -Inf,ymax = Inf,fill = "black",alpha = 0.3) +
geom_area(size = 1,col = "#f08080",fill = "#f08080",alpha = 0.5)
如果我在 xscale 上将其从 -Inf 扩展到 Inf:annotate("rect",alpha = 0.3) +
然后它给出错误 错误:无效输入:date_trans 仅适用于 Date 类的对象
解决方法
问题在于 scales::date_trans()
转换不能优雅地处理数字输入。我通过手动构建无限日期找到了解决此问题的 workaround。下面是标准数据集的示例:
library(ggplot2)
ggplot(economics,aes(date,unemploy)) +
geom_line() +
annotate("rect",xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,fill = "black",alpha = 0.5)
#> Error: Invalid input: date_trans works with objects of class Date only
# Manually constructing infinite dates
ggplot(economics,xmin = structure(-Inf,class = "Date"),xmax = structure(Inf,alpha = 0.5)
由 reprex package (v1.0.0) 于 2021 年 4 月 20 日创建
I've argued 在此之前,理想情况下, scales 包中的日期和时间转换应该更灵活地处理此类情况。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。