Reputation: 164
Suppose I have a data frame with records (Value
) for 100 subjects
(Subject
), which were measured with three different methods
(Method
). Now I would like to plot Value
from each method against
each other, so in this case "base-new", "base-edge" and "new-edge". How
can I do this in ggplot2
based on a single numeric variable using
facet_wrap
?
dummy <- data.frame(Value = c(rnorm(100, mean = 35, sd = 2),
rnorm(100, mean = 47, sd = 2),
rnorm(100, mean = 28, sd = 1)),
Method = c(rep("base", times = 100),
rep("new", times = 100),
rep("edge", times = 100)),
Subject = rep(paste0("M", seq_len(100)), times = 3))
str(dummy)
## 'data.frame': 300 obs. of 3 variables:
## $ Value : num 32.9 32.2 37 36.6 33 ...
## $ Method : Factor w/ 3 levels "base","edge",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ Subject: Factor w/ 100 levels "M1","M10","M100",..: 1 13 24 35 46 57 68 79 90 2 ...
This code does not work and is just meant as an illustration for what I would like to do:
library("ggplot2")
ggplot(dummy, aes(Value)) +
geom_point() +
facet_wrap(~ Method)
This would be my solution using base R
:
opar <- par()
par(mfrow = c(1, 3))
plot(dummy[dummy$Method == "base", "Value"],
dummy[dummy$Method == "new", "Value"],
xlab = "base", ylab = "new")
plot(dummy[dummy$Method == "base", "Value"],
dummy[dummy$Method == "edge", "Value"],
xlab = "base", ylab = "edge")
plot(dummy[dummy$Method == "new", "Value"],
dummy[dummy$Method == "edge", "Value"],
xlab = "new", ylab = "edge")
par(opar)
Upvotes: 4
Views: 1720
Reputation: 2190
So while this isn't exactly what you were looking for it comes close: I suggest a matrix of plots with facet_grid
instead:
Your data needs a slightly different format:
set.seed(1234)
dummy <- data.frame(Value = c(rnorm(100, mean = 35, sd = 2),
rnorm(100, mean = 47, sd = 2),
rnorm(100, mean = 28, sd = 1)),
Method = c(rep("base", times = 100),
rep("new", times = 100),
rep("edge", times = 100)),
Subject = rep(paste0("M", seq_len(100)), times = 3))
dummy2 = rbind(cbind.data.frame(x = dummy$Value[1:100], xmet = rep("base", 100), y = dummy$Value[101:200], ymet = rep("new", 100)),
cbind.data.frame(x = dummy$Value[1:100], xmet = rep("base", 100), y = dummy$Value[201:300], ymet = rep("edge", 100)),
cbind.data.frame(x = dummy$Value[101:200], xmet = rep("new", 100), y = dummy$Value[201:300], ymet = rep("edge", 100)))
And your plotting is done with:
library("ggplot2")
ggplot(dummy2, aes(x = x, y = y)) +
geom_point() +
facet_grid(ymet ~ xmet)
Which gives:
Now you could add e.g. a legend in the free field. My starting point was an answer to this question of mine
Upvotes: 1