简体   繁体   English

R ggplot2:列不堆叠

[英]R ggplot2: Columns not stacking

I thought stacking columns was the default action under ggplot2 but that does not seem to be happening for my plot. 我认为堆叠列是ggplot2下的默认操作,但对于我的绘图来说似乎没有发生。 I am trying to take two vectors (may or may not have the same length) and graph them in the same plot as stacked bars. 我正在尝试采用两个向量(长度可以相同或可以不相同),并在与堆叠条形图相同的图中绘制它们。 Here is a simple example: 这是一个简单的示例:

z1<-c(500, 300, 200, 100)
z2<-c(800, 100, 50)

names(z1)<-c("a", "b", "c", "d")
names(z2)<-c("a", "c", "e")

z1<-as.data.frame(z1)
z2<-as.data.frame(z2)

colnames(z1)<-"total"
colnames(z2)<-"total"

ggplot()+ 
    labs(x="", y="") + 
    theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) +
    scale_y_continuous(labels=format_si()) +
    ggtitle("Test") +
    geom_bar(data=z1, aes(x=rownames(z1), y=total),position="identity",stat="identity",
    fill=rgb(red=200, green=0, blue=50, maxColorValue = 255)) +
    geom_bar(data=z2, aes(x=rownames(z2), y=total),position="identity",stat="identity",
    fill=rgb(red=0, green=200, blue=50, maxColorValue = 255))

Gives me: 给我:

在此处输入图片说明

As you can see, the a and c elements are in front of each other instead of stacked. 如您所见,a和c元素位于彼此前面,而不是堆叠在一起。

This type of data organization would work better: 这种类型的数据组织会更好地工作:

z1<-c(500, 300, 200, 100)
z2<-c(800, 100, 50)

names(z1)<-c("a", "b", "c", "d")
names(z2)<-c("a", "c", "e")

z1<-as.data.frame(z1)
z2<-as.data.frame(z2)

colnames(z1)<-"total"
colnames(z2)<-"total"

Add group (z1, z2) to the data 将组(z1,z2)添加到数据

z1$Group <- "z1"
z2$Group <- "z2"

Add the rownames as a variable column 将行名添加为变量列

z1$rnm <- rownames(z1)
z2$rnm <- rownames(z2)

Bind these together 将它们绑定在一起

zt <- rbind(z1, z2)

A much simplified plot 简化图

ggplot(zt, aes(x=rnm, y=total, fill=Group)) +
  geom_bar(stat="identity") 

At its core here, you need to understand aesthetics and what type of data is most efficient with ggplot2. 在这里,您需要了解美学以及使用ggplot2最有效的数据类型。 Having separate calls for each group/data ignores the power of a factor variable with several levels. 对每个组/数据进行单独调用会忽略具有多个级别的因子变量的功能。 For example, experiment with swapping Group for rnm in the example. 例如,在示例中尝试将Group交换为rnm

Just try this: 尝试一下:

df <- rbind(cbind(z1, type=rownames(z1), data='z1'), cbind(z2, type=rownames(z2), data='z2'))
ggplot(df, aes(type, total, fill=data)) + 
  geom_bar(stat="identity") +
  scale_fill_manual(values=c(rgb(red=200, green=0, blue=50, maxColorValue = 255), rgb(red=0, green=200, blue=50, maxColorValue = 255)))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM