ggplot中的颜色与图例中的颜色不对应

时间:2019-05-08 16:16:32

标签: r ggplot2

我从《世界幸福报告》中创建了一个直方图,并对值进行重新排序。但是,我希望绘图中的颜色与图例中的颜色匹配。

ggplot(Top102018, aes(x= reorder(Country, -Life.Ladder), y=Life.Ladder))+
geom_col(aes(fill=Country)) + 
scale_fill_discrete(name = "Country", 
                    labels = c("Finland", "Denmark", "Switzerland","Netherlands","Norway","Austria", "Sweden","New Zealand", "Luxembourg","United Kingdom"))  + 
theme_light()

1 个答案:

答案 0 :(得分:2)

由于行scale_fill_discrete(),颜色与图例不匹配。 如果您想要相同的顺序,也可以在reorder()参数中使用fill,而不仅要在x =

中使用
data.frame(
    Country     = c("Finland", "Denmark", "Switzerland"),
    Life.Ladder = c(10, 20, 15) 
) %>% 
    ggplot(aes(x = reorder(Country, -Life.Ladder), y = Life.Ladder)) + geom_col(aes(fill = reorder(Country, -Life.Ladder))) +
    labs(fill = 'Country')  + 
    theme_light()

enter image description here