Search code examples
rplot

How to plot multple lines in R


I have a data frame with 4 columns, all floating-point numbers. I would like to make a piecewise-line plot. Each curve will have 4 points, 1 curve per row of the dataframe. The x-values should be the values of the dataframe, the y-values the column indices.

In Python I would have done something like this

plt.figure()
for i in range(data.shape[0]):
    plt.plot(data[i], [0,1,2,3], '*-')
plt.show()

I have spent an hour reading forums and trying out different arguments for matplot and ggplot but to no avail.

Here is the result of my python plot

enter image description here

I don't mind using other libraries like ggplot2 or other.

Edit: I forgot to specify an important additional requirement. All of the curves have to be sorted in the order of their column index. For example, consider the following plot

enter image description here

Here, the 3rd curve is not plotted correctly with respect to this additional requirement. Its y-indices go in the order [0, 2, 1, 3], whereas it should be [0, 1, 2, 3]. It is the X-axis that I would like to not be sorted.


Solution

  • Obviously, in Base R this is just the same as in Python.

    clr <- hcl.colors(ncol(m))  ## define colors
    plot.new(); plot.window(xlim=range(m), ylim=c(0, 3))  ## define plot area
    for (i in seq_len(ncol(m))) lines(m[, i], 0:3, type='o', pch=20, col=clr[i])  ## loop
    axis(1); axis(2); box()  ## axes and box
    

    enter image description here


    Data:

    set.seed(42)
    m <- sapply(0:10, \(i) c(-.5, .5, 1.5, 2.5) + i + rnorm(4, 0, .1))