2011-08-09 52 views
10

我有一個x變量和兩個y1和y2變量(總共3列)的數據集。我想將y1對x繪製爲軸上方的柱狀圖,將y2繪製在x軸下面的同一個繪圖中的同一個x上,以使兩個柱狀圖彼此鏡像。如何爲R中的x軸鏡像的兩個變量創建條形圖?

下面的圖D是我想要做的一個例子。

Figure **D**

回答

14

使用ggplot你會去做如下:

設置數據。這裏沒有什麼奇怪的,但明顯的軸下的值將是負面的。

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)) 
) 

疊加使用ggplotgeom_bar。要防止geom_bar彙總數據,請指定stat="identity"。同樣,需要通過指定position="identity"來禁用堆疊。

library(ggplot2) 
ggplot(dat, aes(x=x, y=y, fill=group)) + 
    geom_bar(stat="identity", position="identity") 

enter image description here

0

這與GGPLOT2完成。 首先提供一些數據,並將兩個y一起融化。

library(ggplot2) 

dtfrm <- data.frame(x = 1:10, y1 = rnorm(10, 50, 10), y2 = -rnorm(10, 50, 10)) 
dtfrm.molten <- melt(dtfrm, id = "x") 

然後,使圖形

ggplot(dtfrm.molten, aes(x , value, fill = variable)) + 
    geom_bar(stat = "identity", position = "identity") 

Perhpas別人可以提供具有鹼和/或晶格的例子。

HTH

9

爲基礎的圖形的一些非常小的實施例和lattice使用@ Andrie的示例性數據:

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(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

lattice

barchart(y~x,data = dat, origin = 0, horizontal = FALSE) 

enter image description here

相關問題