ggplot显示相同颜色的因子水平

ggplot显示相同颜色的因子水平

本文介绍了ggplot显示相同颜色的因子水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让ggplot始终对某个因素使用相同的颜色映射。例如:

How can I get ggplot to always utilize the same color mapping for a factor. For instance:

library(ggplot)

## Filter for visual simplification
diamonds2 <- diamonds[1:10,]
ggplot(diamonds2, aes(carat, price, color = cut)) + geom_point()

## Now filtering removes some levels of cut
diamonds3 <- diamonds[1:5,]
ggplot(diamonds3, aes(carat, price, color = cut)) + geom_point()

在第一个散点图因子级别公平中为红色。在第二个图表中,因素水平好变成了红色。
我希望保存映射,而不管过滤是否去除因子水平,以便公平总是映射到红色等等。

In the first scatterplot factor level "Fair" is red. In the second graph the factor level "Good" became red.I want the mapping to be preserved regardless of whether the filtering removes factor levels so that "Fair" is always mapped to red and so on.

实际上我的ggplot要复杂得多。我的原始因素有11个级别。

In reality my ggplot is a lot more complex. My original factor has 11 levels.

MyPalette <- c("#5DD0B9", "#E1E7E9", "#1f78b4", "#a6cee3",  "#de77ae", "#c51b7d", "#8e0152", "#6a3d9a", "#fbdf6f", "#ff7f00", "#fff99")

我在ggplot中引用

which I refer to in ggplot

.. 。scale_fill_manual(values = MyPalette,name =)+ ...


推荐答案

只需使用 MyPalette scale_colour_manual()

Just use a named vector for MyPalette and scale_colour_manual():

MyPalette <- c(Fair = "#5DD0B9", Good = "#E1E7E9", "Very Good" = "#1f78b4", Premium =  "#a6cee3", Ideal = "#de77ae")

ggplot(diamonds2, aes(carat, price, color = cut)) + geom_point() +
  scale_colour_manual(values = MyPalette)

ggplot(diamonds3, aes(carat, price, color = cut)) + geom_point() +
  scale_colour_manual(values = MyPalette)

这篇关于ggplot显示相同颜色的因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:48