【问题标题】:ggplot back-to-back bar charts ignoring factor orderggplot背靠背条形图忽略因子顺序
【发布时间】:2016-03-30 10:11:39
【问题描述】:

我正在尝试创建连续的条形图

Creating a stacked bar chart centered on zero using ggplot

但是,即使我已将填充变量指定为有序因子,我的条形图中填充水平的顺序似乎也被忽略了?

MWE

# Illustrate problem with factors being ignored

mydata <- read.csv(textConnection(
"Attribute, Score, Percent
A1, Poor, 10
A1, Below Avg, 20
A1, Above Avg, 20
A1, Excellent, 50
A2, Poor, 20
A2, Below Avg, 20
A2, Above Avg, 20
A2, Excellent, 40"), as.is=TRUE, strip.white=TRUE, header=TRUE)
mydata$Score <- factor(mydata$Score, 
  levels=c('Poor','Below Avg','Above Avg','Excellent'), order=TRUE)
str(mydata)


myplot <- ggplot(data=mydata, aes(x=Attribute))+
  geom_bar(data=subset(mydata, 
       as.character(mydata$Score) %in% c("Poor","Below Avg")), 
       aes(y= -Percent, fill=Score), stat='identity')+
  geom_bar(data=subset(mydata, 
       !as.character(mydata$Score) %in% c("Poor","Below Avg")),  
       aes(y=  Percent, fill=Score), stat='identity')+
geom_hline( yintercept=0, size=2, color="red")+
coord_flip()

myplot

给予

请注意,填充的级别是按字母顺序排序的,而不是根据排序因子。

谢谢 卡尔·施瓦茨

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是一个具有挑战性的问题。我已经找到了解决方案,但事实是我不明白为什么理性可以解决问题。

    mydata <- mydata[c(2,1,3,4,6,5,7,8), ]
    

    起初我认为问题在于字符的转换因子,但您输入的相同代码效果很好。

    更改图例的顺序似乎是个好主意。

    myplot + scale_fill_discrete(limits=c("Excellent", "Above Avg", "Below Avg","Poor"))
    

    【讨论】:

    • 嗯...很奇怪,数据顺序会影响结果,但您的建议有效...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多