2

我想创建一个通用代码行,我可以将其ggplot应用于我制作的任何分组条形图。我希望它使我的图表对色盲友好。在 libraryggthemes中,该scale_fill_colorblind 函数完成了这项工作。我的问题是黑色经常被选为其中一种颜色。我有时需要叠加置信区间和其他东西,所以黑色并不是真正的选择。

library(ggplot2)
library(ggthemes)
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")+
scale_fill_colorblind()

有没有办法在scale_fill_colourblind一些代码中告诉它不要选择黑色?我不想手动列出颜色,因为我希望它与许多不同的数据兼容(有些可能有两个“填充”,一些 10 等等......)。

任何帮助将不胜感激。

4

3 回答 3

4

充其量是一个黑客,

ggthemes_data$colorblind  <- ggthemes_data$colorblind[-1]
assignInNamespace("ggthemes_data", ggthemes_data, ns="ggthemes")

last_plot() + scale_fill_colorblind()
于 2013-10-10T16:41:43.387 回答
2

另一种选择是使用scale_fill_manualwith ggthemes::colorblind_pal

library(ggplot2)
library(ggthemes)
ggplot(diamonds, aes(clarity, fill = cut)) + 
  geom_bar(position = "dodge") +
  scale_fill_colorblind()


n <- length(unique(diamonds$cut))

# or 
n <- data.table::uniqueN(diamonds$cut)

# Manually fill the geom with breaks provided by the data
#  and getting one extra color from ggthemes::colorblind_pal
#  then dropping black (the first color)
ggplot(diamonds, aes(clarity, fill = cut)) + 
  geom_bar(position = "dodge") +
  scale_fill_manual(breaks = diamonds$cut, 
                    values = colorblind_pal()(n + 1)[-1])
于 2019-03-08T00:41:39.687 回答
1

此答案基于 Alec 的答案,但创建了一个函数,该函数返回scale_fill_discrete的类型参数等于scale_fill_colorblind. 您不必指定数据中的组数;如果有 N 个组,scale_fill_discrete将在其type参数中使用前 N 个颜色。我写的函数还可以让你选择你想要的颜色,所以你可以去掉黑色或使用第 2、第 4 和第 5 种颜色。

加载包

library(ggplot2)
# Included because this is what I used to make the images:
theme_set(theme_minimal()) 
library(ggthemes)

定义颜色/填充函数

# Fill
scale_fill_colorblind7 = function(.ColorList = 2L:8L, ...){
    scale_fill_discrete(..., type = colorblind_pal()(8)[.ColorList])
}

# Color
scale_color_colorblind7 = function(.ColorList = 2L:8L, ...){
    scale_color_discrete(..., type = colorblind_pal()(8)[.ColorList])
}

的默认值.ColorList2:8因为色盲调色板中有8种颜色,第一种是黑色(我们要掉的那个)。

用法

像使用任何其他函数一样使用这些scale函数:

ggplot(diamonds, aes(clarity, fill = cut)) + 
  geom_bar(position = "dodge") +
  scale_fill_colorblind7()

钻石净度直方图(按切工)

您还可以指定中断作为...参数的一部分。它们被传递给...in scale_fill_discrete

ggplot(diamonds, aes(clarity, fill = cut)) + 
  geom_bar(position = "dodge") +
  scale_fill_colorblind7(breaks = diamonds$cut)

钻石净度直方图(按切工)

不喜欢那些颜色?告诉函数使用哪些颜色(它们的位置):

ggplot(diamonds, aes(clarity, fill = cut)) + 
  geom_bar(position = "dodge") +
  scale_fill_colorblind7(.ColorList = c(3,4,7,6,1))

钻石净度直方图(按切工)

于 2022-01-27T22:50:30.240 回答