R 如何对ggplot2中的几何体对象应用渐变填充?
我正在使用ggplot2构建一个时间序列折线图,该折线图利用几何体对象突出显示特定的时间序列事件 出于纯粹的美学原因,我感兴趣的是对几何体对象应用渐变,使其随着y的增加而褪色为白色/透明 我读过其他答案,其中有人建议或geom_光栅可以提供解决方案。我在这方面运气不好。。。对我来说,几何校正似乎是一个明显的选择,因为我可以指定时间序列的开始和结束作为边界。然而,我希望我能被证明是错的!如果有人有任何指导,我们将不胜感激。到目前为止,我的努力是:R 如何对ggplot2中的几何体对象应用渐变填充?,r,ggplot2,R,Ggplot2,我正在使用ggplot2构建一个时间序列折线图,该折线图利用几何体对象突出显示特定的时间序列事件 出于纯粹的美学原因,我感兴趣的是对几何体对象应用渐变,使其随着y的增加而褪色为白色/透明 我读过其他答案,其中有人建议或geom_光栅可以提供解决方案。我在这方面运气不好。。。对我来说,几何校正似乎是一个明显的选择,因为我可以指定时间序列的开始和结束作为边界。然而,我希望我能被证明是错的!如果有人有任何指导,我们将不胜感激。到目前为止,我的努力是: ## READ DATA file = "Dat
## READ DATA
file = "Data.csv"
timeSeries <- read.csv(file, header=TRUE)
## CONVERT DATA TO DATE CLASS
timeSeries$Date <- as.Date(timeSeries$Date, "%d/%m/%y")
timeSeries$Date <- as.Date(format(timeSeries$Date, "19%y-%m-%d"))
## SET GEOM_RECT DATA FRAME
event <- c("Event1", "Event2", "Event3")
startDate <- c("15/06/15", "12/07/17", "6/09/18")
finishDate <- c("9/01/16", "18/11/17", "5/11/18")
dates <- cbind(event, startDate, finishDate)
dates <- as.data.frame(dates, rownames=NULL, stringsAsFactors=FALSE)
dates$startDate <- as.Date(dates$startDate, "%d/%m/%y")
dates$startDate <- as.Date(format(dates$startDate, "19%y-%m-%d"))
dates$finishDate <- as.Date(dates$finishDate, "%d/%m/%y")
dates$finishDate <- as.Date(format(dates$finishDate, "19%y-%m-%d"))
## PLOT USING GGPLOT
plot <- ggplot(timeSeries) +
geom_rect(data=dates, aes(xmin=startDate, xmax=finishDate, ymin=0, ymax=25), fill="blue", alpha=0.4) +
geom_line(aes(x=Date, y=Event)) +
scale_x_date(labels=date_format("19%y")) +
ggtitle("") +
xlab("Time Series") +
ylab("Number") +
theme_minimal()
plot
##读取数据
file=“Data.csv”
timeSeries以下是我对@baptiste想法的实现。看起来很漂亮
ggplot_grad_rects <- function(n, ymin, ymax) {
y_steps <- seq(from = ymin, to = ymax, length.out = n + 1)
alpha_steps <- seq(from = 0.5, to = 0, length.out = n)
rect_grad <- data.frame(ymin = y_steps[-(n + 1)],
ymax = y_steps[-1],
alpha = alpha_steps)
rect_total <- merge(dates, rect_grad)
ggplot(timeSeries) +
geom_rect(data=rect_total,
aes(xmin=startDate, xmax=finishDate,
ymin=ymin, ymax=ymax,
alpha=alpha), fill="blue") +
guides(alpha = FALSE)
}
ggplot_grad_rects(100, 0, 25) +
geom_line(aes(x=Date, y=Event)) +
scale_x_date(labels=date_format("19%y")) +
ggtitle("") +
xlab("Time Series") +
ylab("Number") +
theme_minimal()
ggplot_grad_rects您有两个选项:i)沿y离散矩形,并将填充或alpha映射到该变量;ii)对绘图进行后期处理,例如通过gridSVG,它支持本机梯度填充。网上有几个例子(grid.garnish IIRC)谢谢@baptiste,我更喜欢在ggplot中完成这一切。我将如何实现方案一)?我以前没能将渐变映射到几何体对象?嘿@tonytonov,非常感谢。它工作完美,看起来很棒。非常感谢。