让我们考虑以下 R 代码:
x=seq(1,10,1)
y1=runif(10,0,1)
y2=runif(10,0,1)
y3=runif(10,100,200)
matplot(x,cbind(y1,y2,y3),type="l")
这里, 和 的范围y1
与的范围y2
不同y3
。结果,当我创建这个时,和matplot
的曲线在底部是直线,而对应的曲线没有问题。y1
y2
y3
有什么方法可以让我们在同一张图中正确地绘制范围差异很大的曲线?
There are plenty of good examples around of plotting a single plot with two different scales, e.g. https://www.r-bloggers.com/r-single-plot-with-two-different-y-axes/ However, those usually require the usage of par(new=t)
, which would usually require a bit of tweaking, i.e. not always intuitive for data exploration.
I would recommend using ggplot
and facet_wrap
to plot the lines out in different frames on the same image:
library(ggplot2)
out <- data.frame(x=rep(x,3), y=c(y1, y2, y3), gp=unlist(lapply(c("y1", "y2", "y3"), rep, 10)))
ggplot(out, aes(x, y)) + geom_line()+ facet_wrap(~gp, scales="free_y", nrow=3)
最简单的方法是对 y 轴使用对数刻度:
matplot(seq(1, 10, 1), cbind(runif(10, 0, 1), runif(10, 0, 1), runif(10, 100, 200)),
type = "l", log = "y")
您可以使用以下方法获得类似的结果ggplot2
:
library(tidyr)
library(ggplot2)
df1 = data.frame(x = seq(1, 10, 1),
y1 = runif(10, 0, 1),
y2 = runif(10, 0, 1),
y3 = runif(10, 100, 200))
df1 %>%
gather(y, value, -x) %>%
ggplot(aes(x, value)) + geom_line(aes(color = y)) + scale_y_log10()
如果您不想要对数轴,另一种选择是带有自由轴刻度的刻面:
df1 %>%
gather(y, value, -x) %>%
ggplot(aes(x, value)) + geom_line() + facet_grid(y ~ ., scales = "free")