2012-03-24 68 views
4

我有以下數據Barplot與2個變量,2 y軸

test<-data.frame(group=1:10, var.a=rnorm(n=10,mean=500,sd=20), var.b=runif(10)) 

我想與2個y軸的(一個用於var.a,一個用於var.2)一個barplot。每組(x軸,1:10)應該有2個相鄰的小節,一個用於var.a,另一個用於var.b.

我不能使用一個Y軸,因爲var.a和var.b

的大小的差的morder這是可能的基礎R?

謝謝

回答

7

要使用graphics包中的R,人們可以在var.avar.b轉換成最大值的比例在各可變創建新的變量的值:

test <- data.frame(group = 1:10, var.a = rnorm(n = 10, mean = 500, sd = 20), 
    var.b = runif(10)) 

funProp <- function(testCol) { 
    test[, testCol]/max(test[, testCol]) 
} 

test$var.a.prop <- funProp("var.a") 
test$var.b.prop <- funProp("var.b") 

然後使用不帶軸的barplot()繪製繪圖:

barplot(t(as.matrix(test[, c("var.a.prop", "var.b.prop")])), beside = TRUE, 
    yaxt = "n", names.arg = test$group) 

然後使用標籤的原始值範圍(labels參數)和比例值範圍將左側和右側的軸添加到軸上(at參數)(這部分不漂亮,但它不漂亮幹得不錯):

axis(2, at = seq(0, max(test$var.a.prop), length.out = 10), 
    labels = round(seq(0, max(test$var.a), length.out = 10))) 

axis(4, at = seq(0, max(test$var.b.prop), length.out = 10), 
    labels = round(seq(0, max(test$var.b), length.out = 10), 2)) 

(對不起,沒有圖像的)

編輯:

要獲得軸位pretty呃,

myLeftAxisLabs <- pretty(seq(0, max(test$var.a), length.out = 10)) 
myRightAxisLabs <- pretty(seq(0, max(test$var.b), length.out = 10)) 

myLeftAxisAt <- myLeftAxisLabs/max(test$var.a) 
myRightAxisAt <- myRightAxisLabs/max(test$var.b) 

barplot(t(as.matrix(test[, c("var.a.prop", "var.b.prop")])), 
    beside = TRUE, yaxt = "n", names.arg = test$group, 
    ylim=c(0, max(c(myLeftAxisAt, myRightAxisAt)))) 

axis(2, at = myLeftAxisAt, labels = myLeftAxisLabs) 

axis(4, at = myRightAxisAt, labels = myRightAxisLabs) 
+0

非常聰明的方法。非常感謝你。有什麼辦法讓軸看起來更漂亮一些? – ECII 2012-03-25 08:32:33

+1

@ECII,請參閱上面的編輯,以獲得更漂亮的軸的建議。 – BenBarnes 2012-03-25 19:15:21