我正在使用ggplot2构建时序折线图,该时序图利用geom_rect对象突出显示特定的时序事件。

出于纯粹的美学原因,我对将渐变应用于geom_rect对象感兴趣,以便随着y的增加渐变为白色/透明。

在建议geom_tile或geom_raster可以提供解决方案的地方,我还阅读了其他答案。我对此没有运气...对我来说,geom_rect似乎是显而易见的选择,因为我可以将时间序列的开始和结束指定为边界。但是,我希望可以证明我做错了!如果有人有任何指导,将不胜感激。到目前为止,我的尝试是:

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

上面的代码应生成此图。可以从here下载数据。

最佳答案

这是我对@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()

关于r - 如何在ggplot2中的geom_rect对象上应用渐变填充?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29728082/

10-12 13:59