基于R中日期列的颜色散点图

Color scatter plot based on Date column in R

我有一个包含三列的数据框:日期、X 和 Y。我想在 X 和 Y 之间绘制一个散点图,并根据“日期”列为散点添加颜色。该图还应显示颜色条(带有标签 min(Date) 到 max(Date))。

下面是示例数据框:

df <- structure(list(Date = structure(c(17471, 17472, 17473, 17474, 17475, 17476, 17477, 17478, 17479, 17480), class = "Date"), X = c(0.796174166775646,  0.848555231972632, 0.683680046726043, 0.686642470840829, 0.720126049914675,  0.627708683319572, 0.592784894803222, 0.49770995584235, 0.92458842974608,  0.776247170913462), Y = c(0.855872728731457, 0.730466555438912,  0.733560880833523, 0.847513809554321, 0.766668352652661, 0.731916270305317, 0.657927669736621, 0.488083725626701, 0.771059482797226, 0.866358366092603 )), row.names = c(NA, 10L), class = "data.frame")

以下是我到目前为止所尝试的:

rbPal <- colorRampPalette(c('red','blue'))
df$Col <- rbPal(10)[as.numeric(cut(df$Date,breaks = 10))]
plot(df$X, df$Y, xlab="X", ylab="Y", xlim=c(0,1), ylim=c(0,1), cex.lab=2, cex.axis=2, cex.main=2, cex.sub=2, pch=20,family = "Times New Roman", col = df$Col)

但是,我没有得到我要找的东西。我想要添加一个连续的颜色条,其中包含从 min(Date) 到 max(Date) 的标签。


library(ggplot2)

ggplot( df, aes(X,Y)) +
  geom_point(shape=21, stroke=1, aes(fill=Date),color="grey",size=6) + 
  scale_fill_gradient(low = "white", high = "black", labels=function(x)as.Date(x, origin="1970-01-01") )

我很惊讶日期的灰度颜色渐变看起来多么笨拙。