4

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

我的数据 ( 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

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

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')

但收到以下错误消息:

Error: Discrete value supplied to continuous scale

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

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

目标是让 Date 列指示点的颜色,最早的日期具有红色,较晚的日期具有颜色渐变上的绿色。

4

2 回答 2

6

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

完全是这样:
还请注意,我将col论点移至geom_jitter(not 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")

在此处输入图像描述


先前的响应,使用as.numeric保留进行比较

您可以将列包装在as.numeric. 另外,我将col论点移至geom_jitter(not 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")

在此处输入图像描述

于 2013-08-04T05:23:10.293 回答
1

您可以尝试获取日期列的最小值和最大值,并将日期映射到 0 到 1 范围内的比例。

df$Date=as.POSIXct(df$Date)
min=min(df$Date)
max=max(df$Date)
as.numeric(difftime(df$Date,min,units='days'))/as.numeric(difftime(max,min,units='days'))

[1] 0.42426474 0.00000000 0.05298048 0.61992950 1.00000000 0.07570895

将其添加到您的数据框中,您应该可以开展业务。

于 2013-08-04T05:23:08.683 回答