2016-03-25 64 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