ggplot2:将两个分箱的条形图放入一个分箱的堆叠条形图中

ggplot2: Put a two binned bar chart into a one binned stacked barchart

Dataset looks like this and is entitled rotterdam3

我正在尝试将其放入一个只有一个箱子的堆叠条中,该箱子是该党根据他们赢得的选票份额的百分比堆叠在一起的。我的代码现在如下。我知道我的问题..它是因为 Party 变量中有两个东西,所以它不会把它放入一个变量中。我不确定如何更改此设置。我试图取出 x 参数,但 ggplot 不允许使用 geombar。

 ggplot(rotterdamparty3, aes(Party, PercVote, fill=Variable)) +
  geombar(stat="identity")
xlab("Party") +
ylab("Percent of vote share") +
ggtitle("Total Cote Share between VVD and PVV in Rotterdam") +
theme(axis.title.x=element_blank(),
scale_fill_manual(values=c("darkblue, "chocolate3"), labels=c("VVD", "PVV")) +
theme(text=element_text(size=14, vjust=1, family="Trebuchet MS")) +
theme(panel.background = element_rect(fill='gray95', colour='white'))

您的代码中有一些错误。我冒昧地修复了代码并快速 data.frame.

library(ggplot2) 
library(reshape2) 
## make data.frame:
rotterdamparty3 <- data.frame(Party=c("PVV TK17", "VVD TK17"),
                              Variable=c("PVV", "VVD"),
                              RawVote=c(50260, 51661),
                              PercVote=c(49.3127, 50.6873))



## edit:  geombar -> geom_bar, 
## edit:  put "+" after geom_bar()
## edit:  "darkblue -> "darkblue"
## edit:  "Cote" -> "Vote"
## edit:  moved first theme() instance and closed parenthesis. 
ggplot(rotterdamparty3, aes(Party, PercVote, fill=Variable)) + 
  geom_bar(stat="identity") +   
  xlab("Party") +   
  ylab("Percent of vote share") +   
  ggtitle("Total Vote Share between VVD and PVV in Rotterdam") +   
  scale_fill_manual(values=c("darkblue", "chocolate3"), 
                    labels=c("VVD", "PVV")) +   
  theme(axis.title.x=element_blank(),
        text=element_text(size=14, vjust=1, family="Trebuchet MS"),    
        panel.background = element_rect(fill='gray95', colour='white'))

创建一个 "dummy" X 变量,如果您希望所有内容都在一个柱中,则该变量对不同方具有相同的值。另外,请注意,我认为您在问题中指定标签的方式实际上切换了哪个缔约方具有哪个 PercVote 值 --- 我将标签注释掉并让 ggplot2 自动处理它。如果颜色不属于正确的一方,只需在下面的代码中切换颜色的顺序即可。

## Create X
rotterdamparty3$X <- " "


## Put X into aes()
ggplot(rotterdamparty3, aes(X, PercVote, fill=Variable)) +
  geom_bar(stat="identity")+
  xlab("Party") +
  ylab("Percent of vote share") +
  ggtitle("Total Vote Share between VVD and PVV in Rotterdam") +
  scale_fill_manual(values=c("darkblue", "chocolate3")#, 
                    #labels=c("VVD", "PVV")
  ) +
  theme(axis.title.x=element_blank(),
        text=element_text(size=14, vjust=1, family="Trebuchet MS"),    
        panel.background = element_rect(fill='gray95', colour='white'))