Multiple data points on one plot R ggplot2

I have two sets of data points that are on the same primary axis, but that are different along the secondary axis. Is there a way to tie them together in R using ggplot2?

What I'm looking for basically looks like this:

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

   ... temperatur
   x car sale

(This is just an example of possible data)

+2


source to share


2 answers


I am not an expert on this, but I understand that it is possible with a lattice, but not with ggplot2. See this blog post in block for an example of a secondary axis plot. Also see Hadley's answer to this question .

Here's an example of how to do it in a lattice (from 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()

      

+5


source


Shane's answer, "you can't in ggplot2", is correct if incomplete. This may not be what you want to do. How do you decide how to scale the Y axis? Do you want the line means to be the same? Range? There's no principled way to do this, and it's all too easy to make the results look like whatever you want them to look like. Instead, what you might want to do, especially in a time series like this, is the rate of two rows of data, so for a certain value of t, often min (t), Y1 = Y2 = 100. Here's an example I took off Bonddad's blog (not using ggplot2, so it's ugly!) But you can clearly tell the relative magnification and reduction of two lines that have completely different basic scales.



alt text

+6


source







All Articles