Search code examples
rplotmarginaxis-labelsline-plot

R plot: how can I adjust finicky margins properly?


I am having a problem with margins in my R line plot... I understand there are many questions related to this on the site but none seem to be hitting the nail on the head and so I figured I'll just ask specifically with the details included...I also apologize if overly descriptive/wordy!

I am plotting a R line plot with multiple lines (4) and custom tick marks (character/descriptive info) at time points rather than 0:3. Everything is great except for the margins.

So, first the tick labels are cut off the screen. However, the axis align, legend shows, and all data points show, etc. All looks otherwise correct. Here I set mar = c(5, 4.1, 4.1, 4.0)

I try to change so that labels show by using: mar = c(5, 4.1, 4.1, 4.0) + x), using multiple values for x (0.5, 1.0, 2.5, etc.). This changes the axes so they don't align, graph is cut off, etc. and labels are off screen again.

Next I try to change the dev.new(...) options by using: dev.new(width=4, height=3, unit="in") and other values for w and h. Still no solution... alignment all off, x axis missing, axis labels and tick labels off, etc.

Any assistance is very very much appreciated. I know it can be a finicky plot to use for examples such as this but I prefer R plot over ggplot in this example.

Thank you in advance...

Here is comparable R code:

bird <- c ("2", "4", "3.5", "8")
dog <- c ("8", "6", "10", "4")
fish <- c("10", "8", "5", "1")
cat <- c("12", "6", "3", "1") 

time = c("0", "1", "2", "3")  

  dev.new() 
  plot(time, bird, type="o", col="darkblue", xlab="time points", ylab="average scores of pets", main = "average pet scores over time", ylim=c(0, 15), cex.main=1.2, axes=FALSE) 
  par(las=2, mar = c(5, 4.1, 4.1, 4.0)) 
  axis(1, at=0:3, labels= c("pre-lim", "first appointment", "3 month check-up", "12 month check-up")) 
  axis(2) 
  lines(time, dog, type="o", col="forestgreen") 
  lines(time, fish, type="o", col="cornflowerblue") 
  lines(time, cat, type="o", col="darkturquoise") 
  legend (2.25, 14.3, legend = c("bird", "dog", "fish", "cat"), fill= c("darkblue", "forestgreen", "cornflowerblue", "darkturquoise"))

enter image description here


Solution

  • Combination of dev.new() and par(mar = c(10, 5, 1, 1)) produces decent plot, I think.

    dev.new()
    par(las = 2, mar = c(10, 5, 1, 1)) 
    

    enter image description here