0

让我们考虑以下 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的曲线在底部是直线,而对应的曲线没有问题。y1y2y3

有什么方法可以让我们在同一张图中正确地绘制范围差异很大的曲线?

4

2 回答 2

1

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)

enter image description here

于 2017-04-12T05:03:37.487 回答
1

最简单的方法是对 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")

结果: 在此处输入图像描述

于 2017-04-12T05:00:59.973 回答