Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plot y-axis tick bars at max and min

Tags:

plot

r

I need to plot multiple plots of the same two variables but the range of y values differs across plots. To simplify the y axes, I would like each plot to show only show a tick mark and label at the min and max range on the y axis (min/max of the plot, not the data).

I've played around with the usr and yaxp parameters but no luck. Here's a toy example:

x<-1:10
y<-3:12
plot(x,y,yaxp=c(par("usr")[3],par("usr")[4],1))

I am expecting tick marks/labels corresponding to the top and bottom of the plot along the y axis (with none in-between) but this doesn't end up putting any tick marks or labels on the y axis. Can anyone explain why and how to return the desired outcome?

Thanks!

like image 825
user2414840 Avatar asked Jan 06 '23 06:01

user2414840


1 Answers

Before the plotting actually occurs, the usr values won't be correct for your data. One way to get correct values is to plot first, get the values, and then plot again using those values to place the tick marks:

plot(x, y)

min_tick <- par("usr")[3]
max_tick <- par("usr")[4]

plot(x, y, yaxt = "n") 
axis(side = 2, at = c(min_tick, max_tick))

enter image description here

I'm letting the default labeling occur. That's something that can be customized as desired.

As @42 pointed out, the default plotting behavior for the axis is to extend the data range by 4%. So, the min and max can be calculated using that information, as well:

min_tick <- min(y) - (max(y) - min(y)) * 0.04
max_tick <- max(y) + (max(y) - min(y)) * 0.04
like image 131
Jota Avatar answered Jan 13 '23 14:01

Jota