简体   繁体   中英

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 D below is an example of what I am trying to do.

图** D **

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)

bar_base

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM