嗨,我有一个双条形图。我已经搜索过了,但我无法得到我想要的东西。搜索示例。
Reverse fill order of stacked bars with faceting
R - ggplot2 reverse order of bar
In ggplot2 for R, how do I reverse the order of the bar colors?
不幸的是,我没有足够的声誉来发布图片:(
这是我的代码:
dat9 <- data.frame(
Response = factor(c("Yes","Yes","Yes","Yes","Yes","No", "No", "No", "No", "No")),
Category = factor(c("Under 45","45-64","65+","Men","Women","Under 45", "45-64", "65+", "Men", "Women"), levels=c("Under 45","45-64","65+", "Men", "Women")),
percentage = c(79, 69, 44, 65, 72, 16, 22, 39, 25, 20))
ggplot(data=dat9, aes(x=Category, y=percentage, fill=Response,)) +
geom_bar(stat="identity", position=position_dodge(), colour="black")
(发布PNG的声誉不够!)
我想要反转图像中的红色和蓝色条。同时反转图例中的蓝色和红色框。
更新(已添加PNG)
答案 0 :(得分:0)
您应该重新排列Response的因子级别。默认情况下,因子级别遵循字母顺序,ggplot2遵循此顺序。
dat9 <- data.frame(
Response = factor(c("Yes","Yes","Yes","Yes","Yes","No", "No", "No", "No", "No")),
Category = factor(c("Under 45","45-64","65+","Men","Women","Under 45", "45-64", "65+", "Men", "Women"), levels=c("Under 45","45-64","65+", "Men", "Women")),
percentage = c(79, 69, 44, 65, 72, 16, 22, 39, 25, 20))
dat9$Response <- factor(dat9$Response,levels=c("Yes","No"))
ggplot(data=dat9, aes(x=Category, y=percentage, fill=Response,)) +
geom_bar(stat="identity", position=position_dodge(), colour="black")
答案 1 :(得分:0)
您可以使用scale_fill_manual来选择条形的顺序和颜色。这也解决了图例键框的对角线。
ggplot(data=dat9, aes(x=Category, y=percentage, fill=Response,)) +
geom_bar(stat="identity", position=position_dodge()) +
scale_fill_manual(values = c("blue", "red"))