gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:03:42 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to assign colors to categorical variables in ggplot2 that have stable mapping?

(5 个回答)


6年前关闭。




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

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()

在第一个散点图中,因子水平“公平”是红色的。在第二张图中,因子水平“良好”变为红色。
无论过滤是否删除因子级别,我都希望保留映射,以便“公平”始终映射为红色等等。

实际上,我的 ggplot 要复杂得多。我的原始因子有 11 个级别。
MyPalette <- c("#5DD0B9", "#E1E7E9", "#1f78b4", "#a6cee3",  "#de77ae", "#c51b7d", "#8e0152", "#6a3d9a", "#fbdf6f", "#ff7f00", "#fff99")

我在 ggplot 中提到的
... scale_fill_manual(values = MyPalette, name="") + ...
plot1
plot2

最佳答案

只需为 MyPalette 使用命名向量和 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)

enter image description here

enter image description here

关于r - ggplot 为因子水平显示相同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35781783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com