【问题标题】:How do I join points from a time series in a ggplot representing two variables?如何在表示两个变量的 ggplot 中连接时间序列中的点?
【发布时间】:2021-08-15 00:44:19
【问题描述】:

我正在绘制多个时间序列 (17),其中有 2 个变量,这意味着每个时间序列每年有 2 个值,我想根据另一个变量绘制一个变量。然后我想按年份的顺序用线连接点,这样每个时间序列都会有一条对应的线连接它们的所有点。 有谁知道如何做线连接部分?

我正在使用 ggplot,这是一些脚本、我拥有的情节和我的数据的屏幕截图:

moyvar_plot <- ggplot(moyvar, aes(x=value, y=var$value, group=programme, col=variable)) +
geom_text(aes(label=variable), size=3) +
xlim(0.85, 1.4) +
ylim(0, 1.0) +
ggtitle("Variances sur 5 ans glissants des taux de croissance des nombres de couples \n en fonction des moyennes sur 5 ans glissants des taux de croissance des nombres de couples") +
xlab("Moyenne") + 
ylab("Variance")        

print(moyvar_plot)

其中“变量”是年份数,我正在尝试根据“值”绘制var$value

我尝试根据“程序”对我的数据进行分组,这是我不同时间序列的标识符,并添加了一个 geom_line,但它按 x 轴的顺序连接点,我希望它们按顺序连接年...
这是数据集:

剧情如下:

【问题讨论】:

  • “按年份顺序”而不是按 x 轴连接它们是什么意思?比如,依次为 1-2-3-4-5-6-...39?但是每年有很多编号variable,所以您是否希望它们也按programme 分组?例如,某些行应该为每个programme 组按顺序连接variable 数字?
  • 是的,就是这样!

标签: r ggplot2


【解决方案1】:

您可以使用geom_path() 连接“按照它们在数据中出现的顺序观察”(来自其 R 文档)。

这是一个与您的数据相似的示例。

library(ggplot2)

set.seed(2021) # for reproducible random values in the example data

moyvar <- data.frame(programme = factor(rep(c('a','b','c'), each = 4)), 
    variable = 1:4, value = runif(12), variance = runif(12))

ggplot(moyvar, aes(x = value, y = variance, col = programme)) + 
    geom_text(aes(label = variable), size = 6) + 
    geom_path()

每个programme 行按顺序从variable“1”到variable“4”。

但是,请注意,如果您的 moyvar$variable 由于某种原因在数据集中没有按顺序排列(例如,如果数据集按 moyvar$value 排序),则该行路径不会按顺序连接variable 数字。

您可以通过在绘制之前重新排序行来解决它。以下是确保您的数据按需要排序的几种方法:

moyvar <- moyvar[order(moyvar$variable),]

#or

moyvar <- dplyr::arrange(moyvar, variable) # requires `dplyr` package

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2022-06-15
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2023-02-19
    相关资源
    最近更新 更多