0
votes

I am plotting multiple time series (17) in which there are 2 variables, which means 2 values for each year for each time series, and I want to plot one variable according to the other. And then I want to join the points with lines in order of year, so that each time series will have a corresponding line joining all their points. Does anyone know how to do the line-joining part?

I am working with ggplot, here's some script, a plot I have and a screenshot of my data:

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)

In which "variable" is the year number, and I am trying to plot var$value according to "value".

I have tried grouping my data according to "programme", which is the identifier of my different time series, and adding a geom_line, but it connects the point in order of the x axis, and I want them connected in order of year...
This is the dataset: enter image description here

This the plot: enter image description here

1
What do you mean by connecting them "in order of year" and not by x-axis? Like, sequentially 1-2-3-4-5-6-...39? But there are many of each year number variable, so do you want them to be grouped by programme as well? As in, some lines are supposed to connect the variable numbers sequentially for each programme group?LC-datascientist
Yes, that's it exactly!Anne

1 Answers

0
votes

You can use geom_path() to connect "the observations in the order in which they appear in the data" (from its R documentation).

Here is an example that is similar to your data.

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

enter image description here

Each programme line goes sequentially from variable "1" to variable "4".

However, duly note that if your moyvar$variable, for some reason, is not ordered sequentially in the data set (e.g., if the data set is sorted by moyvar$value), the line paths will not connect the variable numbers sequentially.

You can resolve it by reordering the rows before you plot. Here are a couple ways to make sure your data is sorted as desired:

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

#or

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