英文:
Connecting neighboured points of categorial time series - ggplot
问题
I have time series data: 10 second intervals (x), in each interval behavioural categories are coded (-1, 0, 1, 2, 3) (y).
我有时间序列数据:10秒间隔(x),在每个间隔内,行为类别被编码为(-1,0,1,2,3)(y)。
I plot individuals to get a visual impression of potential patterns. So far I have the plot below and my goal is to connect points next to each other within each category of y. So that it does not look like single points but like continuous lines as long as one behavior is coded.
我绘制个体以获取潜在模式的视觉印象。到目前为止,我有下面的绘图,我的目标是连接在每个y类别内彼此相邻的点。这样它看起来不像单个点,而是像只要有一个行为被编码就连续的线。
Here is the code for my plot so far:
以下是我目前绘图的代码:
geom_point(colour = "blue", shape = 15) +
theme_minimal() +
theme(panel.grid.minor = element_blank()
I tried with adding geom_step() but this did not lead to the desired result (because it connects all points across categories of y):
我尝试添加geom_step(),但这没有得到期望的结果(因为它连接了所有y类别中的点):
英文:
I have time series data: 10 second intervals (x), in each interval behavioural categories are coded (-1, 0, 1, 2, 3) (y).
I plot individuals to get a visual impression of potential patterns. So far I have the plot below and my goal is to connect points next to each other within each category of y. So that it does not look like single points but like continuous lines as long as one behavior is coded.
Here is the code for my plot so far:
ggplot(data = data_onedyad, aes(x = Sequence, y = Code_m, group = CoupleID)) +
geom_point(colour = "blue", shape = 15) +
theme_minimal() +
theme(panel.grid.minor = element_blank()
I tried with adding geom_step() but this did not lead to the desired result (because it connects all points across categories of y):
答案1
得分: 2
你可以使用运行长度编码来识别相同值的序列。vctrs::vec_identify_runs()
,dplyr::consecutive_id()
或data.table::rleid()
返回一个值属于哪个运行,这在你的情况下是一个很好的分组变量。
library(ggplot2)
df <- data.frame(
x = factor(1:20),
y = sample(c(-1, 0, 1), 20, replace = TRUE)
)
ggplot(df, aes(x, y)) +
geom_point() +
geom_line(aes(group = vctrs::vec_identify_runs(y)),
colour = "red")
Created on 2023-04-19 with reprex v2.0.2
英文:
You can identify sequences of the same values with run length encoding. vctrs::vec_identify_runs()
, dplyr::consecutive_id()
, or data.table::rleid()
return to what run a value belongs, which makes a good grouping variable in your case.
library(ggplot2)
df <- data.frame(
x = factor(1:20),
y = sample(c(-1, 0, 1), 20, replace = TRUE)
)
ggplot(df, aes(x, y)) +
geom_point() +
geom_line(aes(group = vctrs::vec_identify_runs(y)),
colour = "red")
<!-- -->
<sup>Created on 2023-04-19 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论