【问题标题】:ggplot2: Put a two binned bar chart into a one binned stacked barchartggplot2:将两个分箱条形图放入一个分箱堆叠条形图中
【发布时间】:2017-06-26 15:09:51
【问题描述】:

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

【问题讨论】:

  • 我的数据集是什么样子的链接在我的问题顶部。谢谢大家!

标签: r ggplot2 rstudio geom-bar


【解决方案1】:

您的代码中有一些错误。我冒昧地修复了代码并制作了一个快速的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'))

如果您希望所有内容都在一个栏中,请创建一个“虚拟”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'))

【讨论】:

  • 谢谢!这非常有帮助并且效果很好。我还能够将您的代码转移到我的其他一些工作中。也感谢您的编辑:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
相关资源
最近更新 更多