简体   繁体   English

R:从 plot 镜像 y 轴

[英]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.我有一个热图,(但我想这适用于每个情节)但我需要镜像我的 y 轴。

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.但我需要镜像 y 轴。 Starting with 0 on the top and 50 on the bottom.从顶部的 0 和底部的 50 开始。 Does anybody has a clue as to what I must do to change this?有没有人知道我必须做些什么来改变这一点?镜像热图

See the help page for?plot.default, which specifies请参阅帮助页面?plot.default,它指定

xlim: the x limits (x1, x2) of the plot. xlim:plot 的 x 限制 (x1, x2)。 Note that 'x1 > x2' is allowed and leads to a 'reversed axis'.请注意,“x1 > x2”是允许的,并导致“反转轴”。

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". plotrix package 中的 revaxis function “反转了‘x’和‘y’轴中的一个或两个的意义”。 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.它不能解决您的问题(Nick 的解决方案是正确的),但是当您需要 plot 一个带有反向轴的散点图时会很有用。

I would use rev like so:我会像这样使用rev

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

In case you were not aware, notice that df is actually a function.如果您不知道,请注意df实际上是 function。 You might want to be careful when overwriting.覆盖时您可能需要小心。 If you rm(df) , things will go back to normal.如果你rm(df) ,事情将 go 恢复正常。

Don't forget to relabel the y axis as Nick suggests.不要忘记按照尼克的建议重新标记 y 轴。

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? R - 像素矩阵的图像?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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