我有以下内容:
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。但是,当我尝试使用此代码时,图像会移动。
结果如下:
这究竟是什么问题?
答案 0 :(得分: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)
我认为结果看起来像你想要的那样:
基于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")
结果看起来很不错:
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"))