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

查看:869
本文介绍了如何更改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的整数内的a,其中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天全站免登陆