ggplot2:单独的颜色一类别 [英] ggplot2 : Color One Category Separately

查看:786
本文介绍了ggplot2:单独的颜色一类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成散点图,其中我的某个类别是其他类别。我希望我的因子变量中的其他类别是它们的颜色,但其他类别是灰色的。当我尝试使用scale_color_manual()函数时,它给我带来的错误是我的类别太少。以下示例使用虹膜数据。

  data(iris)
p1 < - ggplot(iris,aes(x = Sepal.Length,y = Sepal.Width,color = Species))+ geom_point()
p1
p2 < - p1 + scale_color_manual(values = c(virginica=grey))
p2




错误:手动缩放值不足。 3只需要,但只提供1只。


是否可以更改一个类别的颜色,而不考虑因素中的其他值?我宁愿不选择所有三个类别的颜色,因为我实际使用的数据有30-40个类别,其中一个是一致的其他。

解决方案

基于


I'm generating a scatterplot in which one of my categories is an "Other" category. I would like the other categories in my factor variable to be whatever color they are, but the "Other" category to be in gray. When I try to use the scale_color_manual() function, it gives me the error that I have too few categories. The example below uses the iris data.

data(iris)
p1 <- ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,color=Species)) + geom_point()
p1
p2 <- p1 + scale_color_manual(values=c("virginica"="gray"))
p2

Error: Insufficient values in manual scale. 3 needed but only 1 provided.

Is it possible to just change the color of one category, regardless of the other values in the factor? I'd rather not select colors for all three categories, as the data that I'm actually working with has 30-40 categories, one of which is consistently "Other".

解决方案

based on this post you can get ggplot colors with this function:

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

So in your case :

cols = gg_color_hue(length(levels(iris$Species)))

Then you reprogramm the color you want to change and use it for your plot:

cols[levels(iris$Species)=="virginica"]="gray"
p2 <- p1 + scale_color_manual(values=cols)

这篇关于ggplot2:单独的颜色一类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆