如何更改 ggplot2 的 scale_fill_brewer 中一个值的颜色值? [英] How do I change the color value of just one value in ggplot2's scale_fill_brewer?

查看:25
本文介绍了如何更改 ggplot2 的 scale_fill_brewer 中一个值的颜色值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 R 数据框 (df),我在 ggplot2 中将其绘制为条形图,并根据数据框 (df$type) 中的一列进行着色.现在,我使用默认的着色模式 (scale_fill_brewer) 来分配颜色.

I have a R dataframe (df) which I am plotting as a bar graph in ggplot2, and coloring based on a column in the dataframe (df$type). Right now, I am using the default coloring pattern (scale_fill_brewer) to assign colors.

如何将黑色分配给一个值(df$type == -1)并使用 scale_fill_brewer 分配其余颜色?(所有其他 df$types 是从 1 到 X 的一组整数中的一个,其中 X 是唯一值的数量)

How can I assign the color black to one value, ( df$type == -1 )and use scale_fill_brewer to assign the rest of the colors? (all other df$types are a within a set of integers from 1 to X, where X is the number of unique values)

到目前为止,我已经能够通过计算 scale_fill_brewer 用于 N 个不同项目的颜色集然后预先确定黑色并将其传递给 scale_fill_manual.

So far, I have been able to do this manually by figuring out the set of colors scale_fill_brewer uses for N different items then predending the color black and passing that to scale_fill_manual.

rhg_cols1<- c("#000000","#F8766D","#7CAE00","#00BFC4","#C77CFF" )
ggplot(y=values,data=df, aes(x=name, fill=factor(type))) + 
  geom_bar()+ scale_fill_manual(values = rhg_cols1)

问题是我需要一个无需手动分配颜色的解决方案,即使用十六进制颜色计算器计算scale_fill_brewer 的十六进制值.

The problem is that I need a solution that works without manually assigning colors by using a hex color calculator to figuring out the hex values of scale_fill_brewer.

类似:

ggplot(y=values,data=df, aes(x=name, fill=factor(type))) +
  geom_bar()+ scale_fill_brewer(value(-1, "black")

谢谢!

该解决方案必须适用于 30 多种颜色并且适用于 ColorBrewer 的Set2"

The solution must work for more than 30 colors and work for "Set2" of ColorBrewer

推荐答案

RColorBrewer 包包含调色板,您可以使用函数 brewer.pal 返回颜色您选择的调色板.

The package RColorBrewer contains the palettes and you can use the function brewer.pal to return a colour palette of your choice.

例如,5 种颜色的连续蓝色调色板:

For example, a sequential blue palette of 5 colours:

library(RColorBrewer)
my.cols <- brewer.pal(5, "Blues")
my.cols

[1] "#EFF3FF" "#BDD7E7" "#6BAED6" "#3182BD" "#08519C"

您可以在 ?brewer.pal 帮助文件中获得有效调色板名称的列表.这些名称与 ColorBrewer 网站上的名称一致.

You can get a list of valid palette names in the ?brewer.pal help files. These names correspond with the names at the ColorBrewer website.

您现在可以使用或修改结果,并按照您的建议使用 scale_manual_fill 将这些结果传递给 ggplot:

You can now use or modify the results and pass these to ggplot using the scale_manual_fill as you suggested:

my.cols[1] <- "#000000"

library(ggplot2)
df <- data.frame(x=1:5, type=1:5)
ggplot(df, aes(x=x, fill=factor(type))) +
    geom_bar(binwidth=1)+ 
    scale_fill_manual(values = my.cols)

这篇关于如何更改 ggplot2 的 scale_fill_brewer 中一个值的颜色值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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