我正试图创建一个比较Cons和工党在选举中赢得的席位的堆叠条形图(有趣,我知道)。我是R工作室的初学者,到目前为止已经有了这个,这将是完美的,除了.
library(ggplot2)
library(reshape2)
elections <- data.frame(Country = c("England", "NI", "Scotland", "Wales"),
Con = c(291, 0, 13, 8), Lab = c(200, 0, 7, 28))
elections_long <- melt(elections, id = "Country")
ggplot(elections_long, aes(x = Country, y = value)) +
geom_bar(stat="identity", aes(fill = variable)) +
ggtitle("Seats Won By Labour and Conservative In the United Kingdom") +
labs(y= "Amount of Seats Won", x = "Country") +
scale_fill_manual(values = c("#53a0ed", "#f71d1d")) +
labs(fill = "Party")
它产生这个- https://i.stack.imgur.com/WZORA.png
它非常接近我想要的,但R Studio却增加了我对工党的任何价值,并使之成为保守党的一部分。
在我的代码中,有什么明显的东西是我遗漏的吗?或者我可以写点什么来阻止保守党的数据吸收工党的数据?
还有--如果有人知道如何翻转最后一栏,使保守党“领先”工党(工党在我的数据中获得了更多的席位--但相反,保守党坐在工党的顶端,个子更高--理想情况下,我希望蓝色的条子小一点,红色的条子上升“在它后面”)。
谢谢!
更新--如果我将第一批数据的编号更改为"91“表示Conserv。它把它画在我想要的地方(在291) --不知道这是一件普通的事情还是什么,但是也许这个信息是有用的!
发布于 2017-10-29 16:13:03
geom_bar
的默认行为是将组叠在一起(见这里),但听起来你不想要一个堆叠的条形图--它看起来只是工党的一个值,是保守党条形图的一部分,因为这些条形图是互相堆叠的。在堆叠的条形图中计算的是条形图的相对高度(而不是绝对高度)。
如果您使用position=position_dodge()
,那么不同的各方将在彼此的旁边进行规划。
library(ggplot2)
library(reshape2)
elections <- data.frame(Country = c("England", "NI", "Scotland", "Wales"),
Con = c(291, 0, 13, 8), Lab = c(200, 0, 7, 28))
elections_long <- melt(elections, id = "Country")
names(elections_long) <- c("Country", "Party", "Votes")
ggplot(elections_long, aes(x = Country, y = Votes, fill = Party)) +
geom_bar(stat="identity", position = position_dodge()) +
ggtitle("Seats Won By Labour and Conservative In the United Kingdom") +
labs(y= "Amount of Seats Won", x = "Country") +
scale_fill_manual(values = c("#53a0ed", "#f71d1d")) +
labs(fill = "Party")
https://stackoverflow.com/questions/47000577
复制相似问题