一个R ggplot2图中的多个数据点

时间:2009-10-09 18:15:47

标签: r graph ggplot2

我有两组数据点,它们都与同一主轴相关,但在辅助轴上有所不同。是否有某种方法可以使用ggplot2在R中将它们绘制在一起?

我正在寻找的东西基本上是这样的:

4+           |
 | x       . + 220
3+     . .   |
 |   x       |
2+   .       + 210
 |     x     |
1+ .     x x |
 |           + 200
0+-+-+-+-+-+-+
     time   

   . temperatur
   x car sale

(这只是可能数据的一个例子)

2 个答案:

答案 0 :(得分:6)

Shane的回答,“你不能在ggplot2中”,如果不完整,那是正确的。可以说,这不是你想要做的事情。你如何决定如何缩放Y轴?你想要线条的方法是一样的吗?范围?没有原则性的做法,而且很容易让结果看起来像你想要的样子。相反,您可能想要做的事情,特别是在这样的时间序列中,是规范两行数据,以便在特定的t值,通常为min(t),Y1 = Y2 = 100.这是一个例子我取消了Bonddad Blog(不使用ggplot2,这就是为什么它很丑!)但是你可以干净地告诉两条线的相对增加和减少,它们具有完全不同的基础尺度。

alt text

答案 1 :(得分:5)

我不是这方面的专家,但我的理解是格子可以做到这一点,但ggplot2不行。 See this leanr blog post表示次轴图的示例。 Also see Hadley's response to this question

以下是如何在格子中进行的示例(来自Gabor Grothendieck):

library(lattice)
library(grid)  # needed for grid.text

# data

Lines.raw <- "Date  Fo  Co
6/27/2007  57.1  13.9
6/28/2007  57.7  14.3
6/29/2007  57.8  14.3
6/30/2007  57  13.9
7/1/2007  57.1  13.9
7/2/2007  57.2  14.0
7/3/2007  57.3  14.1
7/4/2007  57.6  14.2
7/5/2007  58  14.4
7/6/2007  58.1  14.5
7/7/2007  58.2  14.6
7/8/2007  58.4  14.7
7/9/2007    58.7 14.8
"

# in reality next stmt would be DF <- read.table("myfile.dat", header = TRUE)
DF <- read.table(textConnection(Lines.raw), header = TRUE)
DF$Date <- as.Date(DF$Date, "%m/%d/%Y")

par.settings <- list(
        layout.widths = list(left.padding = 10, right.padding = 10),
        layout.heights = list(bottom.padding = 10, top.padding = 10)
)

xyplot(Co ~ Date, DF, default.scales = list(y = list(relation = "free")),
        ylab = "C", par.settings = par.settings)

trellis.focus("panel", 1, 1, clip.off = TRUE)
  pr <- pretty(DF$Fo)
  at <- 5/9 * (pr - 32)
  panel.axis("right", at = at, lab = pr, outside = TRUE)
  grid.text("F", x = 1.1, rot = 90) # right y axis label
trellis.unfocus()