我有一些简单的选举数据:
library(tidyverse)
District_4 <- tibble("Year" = c(2012, 2014, 2016),
"Republican Votes" = c(128568, 84815, 165796),
"Democrat Votes" = c(102222, 51357, 89141),
"Independent Votes" = c(0, 9246, 0))
我正在尝试创建每个选举年的条形图(带有ggplot),y轴为各党派的总投票数,x轴为Year
。我想将按政党划分的投票计数分为3列(Rep,Dem,Ind),这可以由选举年决定,也可以由选举年决定。或者,如果堆叠起来更容易(使用position = "fill"
,那么我对此也很满意。谢谢。
答案 0 :(得分:1)
这样的事情应该让你入门
library(tidyverse)
District_4 %>%
mutate(Year = as.Date(paste0(Year, "/01/01"))) %>%
gather(key, VoteCount, -Year) %>%
ggplot(aes(Year, VoteCount, fill = key)) +
geom_bar(stat = "identity")
或者要并排(而不是堆叠)列,可以在position = "dodge2"
内使用geom_bar
District_4 %>%
mutate(Year = as.Date(paste0(Year, "/01/01"))) %>%
gather(key, VoteCount, -Year) %>%
ggplot(aes(Year, VoteCount, fill = key)) +
geom_bar(stat = "identity", position = "dodge2")
要手动设置颜色
District_4 %>%
mutate(Year = as.Date(paste0(Year, "/01/01"))) %>%
gather(key, VoteCount, -Year) %>%
ggplot(aes(Year, VoteCount, fill = key)) +
geom_bar(stat = "identity", position = "dodge2") +
scale_fill_manual(values = c(
"Democrat Votes" = "grey",
"Republican Votes" = "orange",
"Independent Votes" = "purple"))