2016-03-25 86 views
0

我有如下因素:Barplot轉移中的R

km1 <- c(0.037, 0.066, 0.048, 0.11, 0.105, 0.113, 0.05) 
km2 <- c(0.037, 0.062, 0.048, 0.102, 0.106, 0.116, 0.048) 
km3 <- c(0.032, 0.05, 0.05, 0.1, 0.106, 0.118, 0.042) 
km4 <- c(0.031, 0.052, 0.052, 0.086, 0.09, 0.114, 0.04) 
km5 <- c(0.037, 0.074, 0.046, 0.12, 0.114, 0.132, 0.044) 
km6 <- c(0.037, 0.062, 0.046, 0.1, 0.106, 0.118, 0.042) 
age <- c(30,45,60,75,90,105,120) 

mydata <- matrix(c(km1, km2, km3, km4, km5, km6), nrow = 6, ncol = 7, byrow = TRUE) 

barplot(mydata, beside = TRUE, 
     col = c("yellow","blue","indianred","red2","green","purple"), 
     legend.text = rownames(age), 
     xlab = "age", ylab="GR", 
     ylim=c(0.000, 0.200), 
     xlim=c(30,120), 
     axes=FALSE, las=2) 
box() 
axis(side=1, at=seq(30,120, by=15), cex.axis=0.8, tck=0.02) 
axis(side=2, at=seq(0.000, 0.200, by=0.025), cex.axis=0.8, tck=0.02, las=1) 

我需要每個coloumn的確切日期設置。但是當我試圖使用這些代碼時,圖像會移動。

這裏的結果:

enter image description here

什麼究竟錯呢?

我想要實現這樣的結果: enter image description here

+0

我不完全清楚你想達到什麼樣的目標......你可以張貼你想要的結果嗎?無論如何,罪魁禍首是'xlim'; barplot自動計算列的位置(並將其無形地返回),強制它在30-120之間,你正在移動圖... – digEmAll

回答

0

快速砍:沒有設置xlim並把年齡標籤正是您想要...

res <- barplot(mydata, beside = TRUE, 
    col = c("yellow","blue","indianred","red2","green","purple"), 
    xlab = "age", ylab="GR", 
    ylim = c(0.000, 0.200), 
    axes = FALSE, las=2) 
box() 

axis(side=1, at = colMeans(res), labels=age, cex.axis=0.8, tck=0.02) 
axis(side=2, at=seq(0.000, 0.200, by=0.025), cex.axis=0.8, tck=0.02, las=1) 

我想結果看起來像什麼你想:

enter image description here

一個解決方案基於ggplot2

require(reshape2) 
require(ggplot2) 

mydata2 <- data.frame(km1=km1, km2=km2, km3=km3, 
         km4=km4, km5=km5, km6=km6, age=age) 
datm <- melt(mydata2, value.name="km", variable.name="class", id.vars="age") 
ggplot(datm, aes(x = factor(age), y = km, fill=class)) + 
    geom_bar(stat = "identity", position="dodge", color="black") 

結果看起來相當不錯:

enter image description here


EDIT1:添加水平線

res <- barplot(mydata, beside = TRUE, 
    col = c("yellow","blue","indianred","red2","green","purple"), 
    xlab = "age", ylab="GR", 
    ylim = c(0.000, 0.200), 
    axes = FALSE, las=2) 
box() 
abline(h=(seq(0.000,0.200,0.025)), col="lightgray", lty="dotted") 

axis(side=1, at = colMeans(res), labels=age, cex.axis=0.8, tck=0.02) 
axis(side=2, at=seq(0.000, 0.200, by=0.025), cex.axis=0.8, tck=0.02, las=1) 

EDIT2:手動設置顏色(不推薦)

ggplot(datm, aes(x = factor(age), y = km, fill=class)) + 
    geom_bar(stat = "identity", position="dodge", color="black") + 
    scale_fill_manual(values=c("yellow","blue","indianred","red2","green","purple")) 
+0

你不應該用'4 + 7 *(0:6)因爲barplot計算可能會有所不同。您應該使用barplot的結果值,它指示每列的x座標... – digEmAll

+0

非常感謝!這正是我正在尋找的! –

+0

我強烈建議首先存儲barplot的結果(例如'res < - barplot(...)'),然後替代'4 + 7 *(0:6)'使用'at = colmeans(res)'。 – digEmAll