我对ggplot有疑问。
我有一个包含不同时间点“时间”,x和y坐标(分别名为X_MA和Y_MA)的数据集,请参见我的数据集摘录:
# A tibble: 6 x 9
..1 participant time..3 time..4 time_2 X X_MA Y Y_MA
<dbl> <chr> <dbl> <dttm> <dbl> <dbl> <dbl> <dbl> <dbl>
1 261548 J5Q99IF1 1550093328320 2019-02-13 21:28:48 1 321 321 359 359
2 261549 J5Q99IF1 1550093328353 2019-02-13 21:28:48 2 351 351 485 485
3 261550 J5Q99IF1 1550093328375 2019-02-13 21:28:48 3 387 387 649 649
4 261551 J5Q99IF1 1550093328401 2019-02-13 21:28:48 4 349 349 302 302
5 261552 J5Q99IF1 1550093328419 2019-02-13 21:28:48 5 311 344. 482 455.
6 261553 J5Q99IF1 1550093328438 2019-02-13 21:28:48 6 188 317. 424 468.
我知道如何使用以下代码将整个数据集绘制到热图中:
ggplot(Test_R_TAU_first2sec, aes(x=X_MA, y=Y_MA) ) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
scale_fill_distiller(palette=8, direction=-1) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(legend.position='n_one') +
geom_point(size=1)
不幸的是,图中的所有点都具有相同的颜色(黑色):
。
但是,我希望前2秒的点与后10秒的颜色不同,并在后2秒再次使颜色不同。您知道我必须使用什么命令才能在不同的时间窗口(时间代理变量为time_2)获得这些不同的颜色吗?
我现在尝试了以下代码:
ggplot(Test_R_TAU_2_732019,aes(x = X_MA, y = Y_MA, color = cut(time_2, breaks = c(1,108,1001,1121), labels = c("First two seconds","Middle two seconds","Last period")))) + stat_density_2d(aes(fill =..level..), geom = "raster", contour = FALSE) + scale_fill_distiller(palette=8, direction=-1) + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) + theme(legend.position='n_one') + geom_point(size=1) + guides(color=guide_legend(title="Time category"))
不幸的是,我收到此错误:
Error: (converted from warning) Computation failed in `stat_density2d()`:
missing value where TRUE/FALSE needed
有人可以帮忙吗?
答案 0 :(得分:1)
您可以执行以下操作:
ggplot(data2,aes(x = X_MA, y = Y_MA,
color = cut(time, breaks = c(0,2,12,1000), labels = c("First two
seconds","Middle two seconds","Last period")))) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
scale_fill_distiller(palette=8, direction=-1) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(legend.position='n_one') +
geom_point(size=1) +
guides(color=guide_legend(title="Time category"))
Cut
会将您设置的数据分成多个整数,您可以在此处命名。请注意,您将需要更改间隔的数字-我不知道您的数据集中的第一次读数是什么,但是我已经离开这里进行说明了。
底部的guides
位只是为了命名图例。