带有ggplot和geom_bar的问题:希望两列不加在一起就堆叠在一起

问题描述 投票:0回答:1

我正在制作一个条形图,显示两次选举中有多少票和候选人。我希望将值堆叠在一起,但是这些值会加在一起以使y轴大于应有的值。因此,例如,在x = 23位置,2018年的值应该仅约为800。2019年的值是正确的,但是将两者相加即可使2019年的值大于应有的值。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS90eXdwby5wbmcifQ==” alt =“在此处输入图像描述”>

我不知道如何获得它,以便它向我显示2018年的价值,而在其中堆叠了2019年的价值,而没有将两者加在一起。

这是我正在使用的代码:

ggplot(data = OverallMcCreadyVotes, aes(x=precinct_abbrv, y=McCready,fill=year)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(
    breaks = c("2019","2018"),
    values = c("dark blue","light blue")
  )
r ggplot2 geom-bar
1个回答
0
投票

如果我理解得很好,您想要stacked bar,但从2018年到2019年不增加任何值。

[可能的trick俩(也许还存在其他trick俩,这是我脑海中第一个想到的)俩),那就是从2019年开始操纵您的价值观,使其成为2019年和2018年之间的区别。将被绘制为stack,您将没有值的总和,但有2019年的实际值。

让我通过这个示例进行解释(它来自mtcars数据集,我稍加扭曲以使其更漂亮):

library(tidyverse)
d = mtcars[1:20,]
d <- d %>% group_by(cyl, gear) %>% summarize(M = mean(disp))
d[5,] <- c(8,4,150)
d[6,] <- c(4,3,240)
> d
# A tibble: 6 x 3
# Groups:   cyl [3]
    cyl  gear     M
* <dbl> <dbl> <dbl>
1     4     4  104.
2     6     3  242.
3     6     4  164.
4     8     3  365.
5     8     4  150 
6     4     3  240 

如果我们像您对代码所做的那样进行绘图,则会得到:

library(ggplot2)
ggplot(d, aes(x = cyl, y = M, fill = as.factor(gear)))+
  geom_bar(stat = "identity")

enter image description here

我们最终可以使用position_dodge(0)并具有一定的透明度,但是颜色并不是很好:

ggplot(d, aes(x = cyl, y = M, fill = as.factor(gear)))+
  geom_bar(stat = "identity", position = position_dodge(0), alpha = 0.4)

enter image description here

因此,正如我前面提到的,我们最终可以操纵gear = 3中的值,以使其成为gear 3 = gear3- gear4,我们可以使用tidyrdplyr来实现。 (获得此结果的最可能的方法可能是更简单的方法,但这是我想到的第一个方法,它只是向您展示我们应该获得什么的想法)

library(tidyverse)
d %>% group_by(cyl) %>% pivot_wider(names_from = "gear", values_from = "M") %>%
  mutate(Gear4 = `4`, Gear3 = `3`) %>% mutate(Gear3 = Gear3 - Gear4) %>% select(cyl, Gear4, Gear3) %>%
  pivot_longer(., -cyl, names_to = 'Gear', values_to = "Mean") 

# A tibble: 6 x 3
# Groups:   cyl [3]
    cyl Gear   Mean
  <dbl> <chr> <dbl>
1     4 Gear4 104. 
2     4 Gear3 136. 
3     6 Gear4 164. 
4     6 Gear3  77.7
5     8 Gear4 150  
6     8 Gear3 215. 

现在,如果要绘制它们,您将得到:

ggplot(d, aes(x = as.factor(cyl), y = Mean, fill = Gear)) +
  geom_bar(stat = "identity")

enter image description here

然后您会得到一个堆积的条形图,其中没有gear = 3gear = 4中的值之和。但是,仅当您来自Gear 3的所有值都优于Gear 4的值时,此示例才有效。否则,您将有一些奇怪的条形图。

例如,我个人的观点是将其表示为geom_line

ggplot(d, aes(x = cyl,  y = M, color = as.factor(gear))) + geom_line() + geom_point()

enter image description here

它回答了您的问题吗?

© www.soinside.com 2019 - 2024. All rights reserved.