将日期转换为连续比例/变量

whi*_*ler 4 r ggplot2

无论如何转换或指示ggplot将Dates列解释为连续变量?

我的数据(df)如下所示:

Location       Date     Value
56.28,-36.57 2011-01-10  32
56.28,-36.57 2010-02-08  40
52.24,-36.58 2010-03-22  18
52.24,-36.58 2011-06-14  39
52.25,-36.59 2012-04-10  41
52.25,-36.59 2010-04-09  38
Run Code Online (Sandbox Code Playgroud)

我试图使用以下命令绘制数据:

g=ggplot(df) + geom_boxplot(aes(factor(Location),Value, col=Date))+ geom_jitter(aes(factor(Location),Value),size=1) + scale_colour_gradient(low='red',high='green')
Run Code Online (Sandbox Code Playgroud)

但收到以下错误消息:

Error: Discrete value supplied to continuous scale
Run Code Online (Sandbox Code Playgroud)

如果我将Date转换为Date对象(例如col=as.Date(Date)),我收到以下错误:

Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0
Run Code Online (Sandbox Code Playgroud)

目标是让Date列指示点的颜色,最早的日期颜色为红色,后面的日期颜色渐变为绿色.

Ric*_*rta 5

一种选择是将日期列包装在中as.numeric.但是,正如@Hadley在评论中指出的那样,trans论证中的参数scale_colour_gradient可以取值date.这具有显示日期值而非数字的图例的附加好处(相对于我之前发布的内容).

这里完全是这样的:
请注意我将col参数移到了geom_jitter(不是geom_boxplot)

ggplot(df) + geom_boxplot(aes(factor(Location),Value))           +
    geom_jitter(aes(factor(Location),Value, col=Date),size=2)    +  # <~~~ col
    scale_colour_gradient(trans="date", low="red", high="green") +
    xlab("Location")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


以前的回复,as.numeric保留用于比较

您可以将列包装在中as.numeric.另外,我把col论点移到了geom_jitter(不是geom_boxplot).

ggplot(df) + geom_boxplot(aes(factor(Location),Value))+
    geom_jitter(aes(factor(Location),Value, col=as.numeric(Date)),size=2) +
    scale_colour_gradient(low='red',high='green') + 
    theme(legend.position="none") + xlab("Location")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 而不是做`as.numeric(Date)`,你可以做`scale_colour_gradient(trans = "date")` (2认同)