How do you create a bar plot for two variables mirrored across the x-axis in R?
I have a dataset with an x variable and two y1 and y2 variables (3 columns in total). I would like to plot y1 against x as a bar plot above the axis and y2 against the same x in the same plot underneath the x axis so that the two bar plots mirror each other.
Figure开发者_JAVA百科 D below is an example of what I am trying to do.
Using ggplot
you would go about it as follows:
Set up the data. Nothing strange here, but clearly values below the axis will be negative.
dat <- data.frame(
group = rep(c("Above", "Below"), each=10),
x = rep(1:10, 2),
y = c(runif(10, 0, 1), runif(10, -1, 0))
)
Plot using ggplot
and geom_bar
. To prevent geom_bar
from summarising the data, specify stat="identity"
. Similarly, stacking needs to be disabled by specifying position="identity"
.
library(ggplot2)
ggplot(dat, aes(x=x, y=y, fill=group)) +
geom_bar(stat="identity", position="identity")
Some very minimal examples for base graphics and lattice
using @Andrie's example data:
dat <- data.frame(
group = rep(c("Above", "Below"), each=10),
x = rep(1:10, 2),
y = c(runif(10, 0, 1), runif(10, -1, 0))
)
In base graphics:
plot(c(0,12),range(dat$y),type = "n")
barplot(height = dat$y[dat$group == 'Above'],add = TRUE,axes = FALSE)
barplot(height = dat$y[dat$group == 'Below'],add = TRUE,axes = FALSE)
and in lattice
:
barchart(y~x,data = dat, origin = 0, horizontal = FALSE)
This is done with ggplot2. First provide some data and put the two y together with melt.
library(ggplot2)
dtfrm <- data.frame(x = 1:10, y1 = rnorm(10, 50, 10), y2 = -rnorm(10, 50, 10))
dtfrm.molten <- melt(dtfrm, id = "x")
Then, make the graph
ggplot(dtfrm.molten, aes(x , value, fill = variable)) +
geom_bar(stat = "identity", position = "identity")
Perhpas someone else can provide an example with base and/or lattice.
HTH
精彩评论