Home > Blockchain >  Plot multiple line graphs on the same window with auto-assigned different colors
Plot multiple line graphs on the same window with auto-assigned different colors

Time:07-26

I want to create a vector of functions with two parameters where one parameter is over a continuous range of values and the other runs over a fixed number of numerical values saved in the column vector dat[,2].

# Example functions
icc <- function(year, x) {
  z = exp(year - x)
  inf = z / (1   z)
  return (inf)
}

# Example data
year <- seq(-4, 4, 0.1)
x1 <- dat[1, 2]
x2 <- dat[2, 2]

# Plots
plot(t, icc(year, x1), type = "l")
plot(t, icc(year, x2), type = "l")

The issues are

  1. dat[,2] has more than just 2 values and I want to be able to plot all the corresponding functions on the same plot but with different colors
  2. manually assigning colors to each line is difficult as there are a large number of lines
  3. dat[,1] stores the corresponding label to each plot; would it be possible to add them over each line?

I have something like this in mind-

UPDATE: dat is simply a 40 x 2 table storing strings in the first column and numerical values in the second. By 'a vector of functions', I mean an array containing functions with parameter values unique to each row. For example- if t^i is the function then, element 1 of the array is the function t^1, element 2 is t^2 and so on where t is a 'range'. (Label and color are extras and not too important. If unanswered, I'll post another question for them).

CodePudding user response:

The function to use is matplot, not plot. There is also matlines but if the data to be plotted is in a matrix, matplot can plot all columns in one call.

  1. Create a vector of y coordinates, yy, from the x values. This is done in a sapply loop. In the code below I have called the x coordinates values xx since there is no dat[,2] to work with.
  2. Plot the resulting matrix in one matplot function call, which takes care of the colors automatically.

The lines labels problem is not addressed, only the lines plotting problem. With so many lines their labels would make the plot more difficult to read.

icc <- function(year, x) {
  z = exp(year - x)
  inf = z / (1   z)
  return (inf)
}

# Example data
year <- seq(-4, 4, 0.1)

xx <- seq(-1, 1, by = 0.2)
yy <- sapply(xx, \(x) icc(year, x))
matplot(year, yy, type = "l", lty = "solid")

Created on 2022-07-26 by the reprex package (v2.0.1)


Note

Function icc is the logistic distribution CDF with location x and scale 1. The base R plogis function can substitute for it, the results are equal within floating-point precision.

icc2 <- function(year, x) plogis(year, location = x, scale = 1)

yy2 <- sapply(xx, \(x) icc2(year, x))
identical(yy, yy2)
#> [1] FALSE
all.equal(yy, yy2)
#> [1] TRUE
  • Related