R中的2层条形图

2-layer barplot in R

我正在尝试在 R 中构建一个(有点)复杂的条形图。我的想法是叠加两个图表,其中一个中的条形图比另一个中的条形图宽,这样两个条形图始终可见。

这是我现在拥有的:

# GENERATE THE DATA  
Age = c(50, 55, 60, 65, 70)                                     # Age groups  
Male = c(15.4, 24.3, 37.0, 54.6, 71.1)                          # Death rates for males  
Female = c(8.4, 13.6, 19.3, 35.1, 50.0)                         # Death rates for females  
Deathrate = matrix(c(Male,Female), nrow=length(Age), ncol=2, dimnames=list(Age, c("Male","Female")))         

# GENERATE THE DATA  
barplot(Deathrate[,1], col="red")
par(new=TRUE)
barplot(Deathrate[,2], space=1, col="blue")

现在,如您所见,显示了两个图,但是虽然两个中间条很好地重叠并居中,但所有其他条都没有居中。例如,最右边的蓝色条显示在最右边的红色条的边缘。

有没有人有一个简单的解决方案来使 所有 条柱居中?

谢谢,菲利普

PS 我知道图表不漂亮(重叠图例等)....

您可以使用 add=TRUE 以及 widthspace 的适当值。

barplot(Deathrate[,1], col="red")
barplot(Deathrate[,2], width=0.5, space=c(0.9, 1.4, 1.4, 1.4, 1.4), col="blue", add=TRUE)

barplot 当然没有针对这种情况进行优化。如果你想要更多的控制,为这种类型的情节推出你自己的绘图功能并不难。

cbarplot <- function(x, ..., bcols=c("red","blue"), bwidth=c(.4,.3)) {
    plot(1, type="n", xlim=c(.5,(nrow(x)+.5)), ylim=c(0,max(x)), xaxt="n", ...)
    for(i in 1:ncol(x)) {
        w <- bwidth[i]
        rect(seq_len(nrow(x))-w, 0, seq_len(nrow(x))+w, x[,i], col=bcols[i])
    }
    axis(1, at=1:nrow(x), rownames(x))
}

cbarplot(Deathrate, ylab="Count", xlab="Age")

这是一个使用ggplot2

的解决方案
Death.df <- as.data.frame(Deathrate) # ggplot2 requires a data frame
Death.df$ages <- rownames(Death.df) # add a column with rownames
Death.m <- melt(Death.df, id.vars = "ages") # melt the dataframe to long form

ggplot(Death.m) +
  geom_histogram(aes(x = ages, y = value), stat = "identity", fill = "red", width = 0.4) +
  geom_histogram(aes(x = ages, y = value), stat = "identity", fill = "blue", width = 0.5, position = "dodge") +
  ggtitle("Death Rates of Males and Females\nMales in Red and Females in Blue")

 barplot(as.vector(rbind(Male, Female)),col=c('red','blue'), space=rep_len(1:0,length(Male)*2), beside=T, legend.text=c('Male', 'Female'));

P.S。条形图没有居中,但我认为这样更漂亮。