Sir Ksilem
Sir Ksilem

Reputation: 1205

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 First 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? mirrored heatmap

Upvotes: 2

Views: 9008

Answers (5)

mdsumner
mdsumner

Reputation: 29525

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)))

Upvotes: 6

bill_080
bill_080

Reputation: 4760

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?

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70653

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.

Upvotes: 0

Paolo
Paolo

Reputation: 2815

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.

Upvotes: 0

Nick Sabbe
Nick Sabbe

Reputation: 11956

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

Upvotes: 1

Related Questions