R中的两层柱状图

R中的两层柱状图,r,bar-chart,R,Bar Chart,我试图在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

我试图在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以及适当的宽度和空间值

可以将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")
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的解决方案

下面是一个使用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'));