ggplot2:将两个装箱的条形图放入一个装箱的堆积条形图中

时间:2017-06-26 15:09:52

标签: r ggplot2 rstudio geom-bar

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'))

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误。我冒昧地修改了代码并快速创建了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'))

enter image description here

如果您想要一个条形图中的所有内容,请创建一个“虚拟”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'))

enter image description here