Create multiple step lines and add a legend
R
# Create multiple step lines and add a legend x <- 1:10 y1 <- cumsum ( runif (10)) y2 <- cumsum ( runif (10)) plot (x, y1, type = "s" , lwd = 2, col = "blue" , ylim = c (0, max (y1, y2))) lines (x, y2, type = "s" , lwd = 2, col = "red" ) legend ( "topright" , legend = c ( "Line 1" , "Line 2" ), col = c ( "blue" , "red" ), lwd = 2) |
Output:
- We generate two sets of y-values, y1 and y2, using the cumsum() function. These represent cumulative sums of random uniform values.
- We use the plot() function to create the initial plot for y1. We specify type = “s” to create a step plot, set the line width (lwd) to 2, and use the color blue (col = “blue”). We also set the y-axis limit (ylim) to ensure both lines fit within the plot.
- We add a second step line for y2 using the lines() function. This time, we use the color red (col = “red”).
- To differentiate between the two lines, we add a legend to the top-right corner of the plot using the legend() function. We provide labels for each line (“Line 1” and “Line 2”), specify their respective colors and line widths, and position the legend using “topright”
Step Line Plot in R
Data points are shown as a series of horizontal and vertical steps using step line plots, sometimes referred to as step plots or stair plots, which are a style of data visualisation used in R and other data analysis tools. These charts are especially helpful for displaying data, such as time series or cumulative data, that changes dramatically at precise times. In this post, we’ll look at how to make step-line graphs in R, alter how they look, and analyse the data they display.
Contact Us