gpt4 book ai didi

r - 将日期转换为连续刻度/变量

转载 作者:行者123 更新时间:2023-12-04 10:49:21 24 4
gpt4 key购买 nike

无论如何转换或指示 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

目标是让日期列指定点的颜色,最早日期的颜色为红色,较晚的日期在颜色渐变上为绿色。

最佳答案

一种选择是将日期列括在 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")

enter image description here

之前的回复,使用 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")

enter image description here

关于r - 将日期转换为连续刻度/变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18039816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com