简体   繁体   中英

R: mirror y-axis from a plot

I have this problem. I got a heatmap, (but i suppose this applies to every plot) but I need to mirror my y-axis.

I got here some example code:

library(gstat)
x <- seq(1,50,length=50)
y <- seq(1,50,length=50)
z <- rnorm(1000)
df <- data.frame(x=x,y=y,z=z)
image(df,col=heat.colors(256)) 

This will generate the following heatmap第一张热图But I need the y-axis mirrored. Starting with 0 on the top and 50 on the bottom. Does anybody has a clue as to what I must do to change this?镜像热图

See the help page for?plot.default, which specifies

xlim: the x limits (x1, x2) of the plot. Note that 'x1 > x2' is allowed and leads to a 'reversed axis'.

library(gstat)
x <- seq(1,50,length=50)
y <- seq(1,50,length=50)
z <- rnorm(1000)
df <- data.frame(x=x,y=y,z=z)

So

image(df,col=heat.colors(256), ylim = rev(range(y)))

Does this work for you (it's a bit of a hack, though)?

df2<-df
df2$y<-50-df2$y #reverse oredr
image(df2,col=heat.colors(256),yaxt="n") #avoid y axis
axis(2, at=c(0,10,20,30,40,50), labels=c(50,40,30,20,10,0)) #draw y axis manually

The revaxis function in the plotrix package "reverses the sense of either or both the 'x' and 'y' axes". It doesn't solve your problem (Nick's solution is the correct one) but can be useful when you need to plot a scatterplot with reversed axes.

I would use rev like so:

df <- data.frame(x=x,y=rev(y),z=z)

In case you were not aware, notice that df is actually a function. You might want to be careful when overwriting. If you rm(df) , things will go back to normal.

Don't forget to relabel the y axis as Nick suggests.

For the vertical axis increasing in the downward direction, I provided two ways (two different answers) for the following question:

R - image of a pixel matrix?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM