dave's reads worth sharing

Data Science, Machine Learning, Artificial Intelligence, Visualization, Complex Systems.

Plotting More Than One Data Series in One-Liner

plot of mulitple data series in R

I already covered several ways to plot multiple data series in the same R plot, either using plot, points and lines or using ggplot and using facets. What I didn’t show was probably the easiest (and I mean easiest), way to plot all data series in one plot. Using matplot!

matplot is part of the graphics library and therefore is installed during your normal R installation. It does not need any further installation and you can use it with the usual plot parameters.

Assuming that you have a data frame df with N columns and M observations and that you want to plot all columns against the first column that will provide the x points.

matplot(df[,1], df[, 2:ncol(df)], pch=19)

The above command will plot multiple data series in R in the same plot without further problems and producing the above picture.

The only condition to plot data series with the above command is that the data frame needs to be wide format (and usually it is).

If your data is in the narrow format you need to pivot the data to wide layout before you can plot multiple data series. In R, the conversion between wide and narrow layouts of the data can be accomplished using the tidyr package.