【问题标题】:Facet barplot isn't respecting colorvalues构面条形图不尊重颜色值
【发布时间】:2017-08-02 15:03:24
【问题描述】:

我想要一个多面的条形图。指示总值的条形必须是红色的,其他的必须是蓝色的。
总值由 Desc1="-" 表示。 我有以下代码:

#df contains the following data:                                                                                                        
#Year;Maingroup;Desc1 ;Desc2      ;Value
#2017;A               ;1        ;A1             ;10
#2017;A               ;2        ;A2             ;20
#2017;A               ;-        ;AT             ;30
#2017;B               ;10       ;B10            ;100
#2017;B               ;20       ;B20            ;200
#2017;B               ;-        ;BT             ;300                                                                                                    
#2017;C               ;11       ;C100           ;53
#2017;C               ;22       ;C200           ;54
#2017;C               ;-        ;CT             ;107

#add a new description                                                                                                                  
df <- df %>% unite (Oms,Desc1,Value,sep=' ',remove=FALSE)
#add color indication
df <- df %>% mutate(colv=(ifelse(Desc1=="-      ","Red","Blue")))
#sort into descending order
df <- df %>% arrange(desc(Value))
#plot horizontal barchart
ggplot(df, aes(x=Desc2,y=Value))+
geom_bar(position=position_dodge(),stat="identity",fill=df$colv)+
facet_grid(~Maingroup,scale="free")+
coord_flip()

但是 R 没有以正确的方式着色条。 我究竟做错了什么?

【问题讨论】:

  • 我猜你需要将fill = ... 放在aes() 调用中
  • 感谢您的超级快速响应,试过了,但没有奏效
  • 那么我建议您使用dput 发布一个实际数据(处理后)的最小示例,以便我们尝试看看有什么问题

标签: r bar-chart


【解决方案1】:

您必须在开始时在 aes() 中使用 fill=colv,然后使用 scale_fill_manual() 来定义颜色,如下所示:

ggplot(df, aes(x=Desc2,y=Value, fill=colv))+
geom_bar(position=position_dodge(),stat="identity") +
scale_fill_manual(values = c("blue", "red")) +
facet_grid(~Maingroup,scale="free") +
coord_flip()

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多