Home > Net >  R: how to fix axis extension in base plot
R: how to fix axis extension in base plot

Time:12-08

I have a Rscript script that plots traces as lines. The problem I have is that the offset (the space between y-axis and the start of the plotted lines) changes proportional to the number of data points, the more data points the greater the offset, as shown in the example plots on the page https://mitomap.org/trace.html.

How can I get the offset fixed so it's not affected by the number of data points?

Below are the relevant codes in the script. I also tried ggplot() and got the same problem.

plot(data$x, data$trace1, type="l", col="black", ylim=c(0,50))
lines(data$x, data$trace2 type="l", col="red")
lines(data$x, data$trace3, type="l", col="green")
lines(data$x, data$trace4, type="l", col="#888888")

While on it, any one can suggest four colors that can better distinguish from each other. In the plots on the above pages, the black, green and red colors distinguish from each other very well, but I can't find a satisfying fourth color that can distinguish from all other tree colors very well. For example, brown, magenta are hard to tell from red, blue from black, cyan from green, etc. Yellow and pink are very faint.

CodePudding user response:

You can force plot to not extend the axis range by 4% of the data range (default) by setting the xaxs style parameter. Moreover, you can specify a shared axis range with xlim (see ?par):

plot(..., xaxs = 'i')

In ggplot, you would set the expand argument of the scale, e. g.:

## ggplot code  
scale_x_continous(..., expand = c(0, 0))
## with the expansion helper:
scale_x_continous(..., expand = expansion(mult = 0, add = 0))

For palettes, see colorbrewer.

  • Related