想要并排的Geom酒吧

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

我正在制作一个图表,其 x 轴是州名称,y 轴是投票份额,但在 x 轴上我希望每个州并排大选和州选举数据。然而,在我的输出中,我只能看到一个条形图,另一个条形图混合在其中。

ggplot(BJP.voteshare.2019) +
  geom_bar(aes(x = State_Name, y = voteshare.bjp.x), fill = "blue", stat = "identity", position = "dodge") +
  geom_bar(aes(x = State_Name, y = voteshare.bjp.y), fill = "red", stat = "identity", position = "dodge") +
  geom_text(aes(x = State_Name, y = voteshare.bjp.x, label = round(voteshare.bjp.x, 2)), vjust = -0.5, size = 3, color = "black", position = position_dodge(width = 0.8)) +
  geom_text(aes(x = State_Name, y = voteshare.bjp.y, label = round(voteshare.bjp.y, 2)), vjust = -0.5, size = 3, color = "black", position = position_dodge(width = 0.8)) +
  labs(title = "BJP Vote Share Comparison: State vs General Elections",
       x = "State", y = "Vote Share (%)") +
  scale_fill_manual(values = c("blue", "red"), labels = c("State Elections", "General Elections")) +
  theme_minimal()

Bar chart showing vote share by state with only a single bar per state

r geom-bar
1个回答
0
投票

我将发明一些简单的示例数据来模拟您可能拥有的数据(结论 我不明白它怎么会变成红色......)。

解决方案方面,我想说 ggplot2 是 tidyverse 的一部分,因此对于如何排列数据有自己的看法;它应该是整洁的。 因此,我对其进行了整理,并显示了更精简的代码,这也可能会产生所需的图表。希望对你有帮助。

1)

(BJP.voteshare.2019 <- data.frame(State_Name=LETTERS[1:3],
                                  voteshare.bjp.x=4:6,
                                  voteshare.bjp.y=1:3
                                  ))
library(tidyverse)

ggplot(BJP.voteshare.2019) +
  geom_bar(aes(x = State_Name, y = voteshare.bjp.x), fill = "blue", stat = "identity", position = "dodge") +
  geom_bar(aes(x = State_Name, y = voteshare.bjp.y), fill = "red", stat = "identity", position = "dodge") +
  geom_text(aes(x = State_Name, y = voteshare.bjp.x, label = round(voteshare.bjp.x, 2)), vjust = -0.5, size = 3, color = "black", position = position_dodge(width = 0.8)) +
  geom_text(aes(x = State_Name, y = voteshare.bjp.y, label = round(voteshare.bjp.y, 2)), vjust = -0.5, size = 3, color = "black", position = position_dodge(width = 0.8)) +
  labs(title = "BJP Vote Share Comparison: State vs General Elections",
       x = "State", y = "Vote Share (%)") +
  scale_fill_manual(values = c("blue", "red"), labels = c("State Elections", "General Elections")) +
  theme_minimal()

2)

# make tidy data

(BJP.voteshare.2019_tidy <- pivot_longer(BJP.voteshare.2019,
                                        cols = starts_with("voteshare.bjp")))

ggplot(BJP.voteshare.2019_tidy) +
  aes(x = State_Name, y = value,group=name)+
  geom_col(aes(fill=name),   position = "dodge") +
  geom_text(aes(label = round(value, 2)), vjust = -0.5, size = 3, color = "black", position = position_dodge(width=.8)) +
   labs(title = "BJP Vote Share Comparison: State vs General Elections",
       x = "State", y = "Vote Share (%)") +
  scale_fill_manual(values = c("voteshare.bjp.x"="blue", "voteshare.bjp.y" = "red"), labels = c("State Elections", "General Elections")) +
  theme_minimal()

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