R:ggplot堆积条形图传奇颠倒

时间:2014-12-10 21:39:00

标签: r ggplot2

我想画一个堆积的条形图:

df1 <- data.frame(sex       = factor(c("Female","Female","Male","Male")),
                 time       = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
                 total_bill = c(13.53, 16.81, 16.24, 17.42))
# Stacked bar graph -- this is not what I want
ggplot(data=df1, aes(x=time, y=total_bill, fill=sex)) + geom_bar(stat="identity")

似乎是: enter image description here

我希望右侧的性别传奇与左侧的堆叠顺序相对应,即底部为红色,顶部为蓝色,我该怎么做?

2 个答案:

答案 0 :(得分:3)

试试这个:

ggplot(data=df1, aes(x=time, y=total_bill, fill=sex)) + 
geom_bar(stat="identity") + 
scale_fill_discrete(breaks=c("Male","Female"))

为我工作

答案 1 :(得分:3)

你也可以添加其中任何一个(它们是等效的):

guides(fill = guide_legend(reverse=TRUE))
scale_fill_discrete(guide = guide_legend(reverse=TRUE))

来自Cookbook for R Graphics