在RColorBrewer调色板中省略较亮的颜色以在ggplot2中使用。

6

我想在我的ggplot(条形图)中使用RColorBrewer的“Oranges”调色板中更深的颜色,但我无法做到。 帮帮我。 下面是示例代码:

my_palette = brewer.pal(n = 9, "Oranges")[4:9]


### Bar Plots ###
ggplot(Sample_df, aes(x = Sample_Score), fill = Sample_Score) + 
  geom_bar(stat = "count", width = 0.8) + scale_fill_brewer(palette= my_palette)  + scale_y_log10(labels = comma) +
   labs(title="Distribution of customers according to Sample Score",x="Sample Score", y="Number of Customers") +
     theme(plot.title = element_text(face = "bold", size = 10),
        axis.title.x = element_text(face = "bold", size = 8),  
        axis.title.y = element_text(face = "bold", size = 8), legend.position="none")

2
我们没有 Sample_df。请阅读关于如何提出好问题和如何给出可重现的示例的信息。这将使其他人更容易地帮助您。 - Axeman
不是完全相同的问题,但非常接近:https://dev59.com/4arka4cB1Zd3GeqPiLl3 - camille
1个回答

9
这是因为您正在使用scale_fill_brewer()命令,该命令需要一个RColorBrewer调色板名称(例如"Oranges")。它无法读取您的自定义调色板名my_palette。 取而代之,请使用scale_fill_manual()
我创建了一个可复制的示例:
library(RColorBrewer)
library(ggplot)

set.seed(1234)
df <- data.frame(x=runif(10,0,1), y=runif(10,0,1), c=factor(sample(1:5,10,replace=T)))

ggplot(data=df, aes(x=x,y=y)) + geom_point(aes(color=c)) + scale_color_brewer(palette = 'Oranges')

正如您看到的,我正在调用RColorBrewer调色板"Oranges"。就像您提到的那样,这些颜色非常浅,您可能只想使用更深的颜色。为此,您可以制作自定义调色板并使用scale_color_manual()(或在您的情况下使用scale_fill_manual())来调用它,而不是使用scale_color_brewer()

my_palette <- brewer.pal(name="Oranges",n=9)[4:9]

ggplot(data=df, aes(x=x,y=y)) + geom_point(aes(color=c)) + scale_color_manual(values = my_palette)

现在,这将使用你在my_palette中指定的颜色。


谢谢这个。FYI,scales包中有一个包装函数scales::brewer_pal,用于调用RColorBrewer。 scales::brewer_pal(name = "Oranges")(9)[4:9]可以达到相同的效果。 - James N

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接