使用命令scale_fill_manual()和scal_fill_discrete()在ggplot2直方图上修改颜色

问题描述 投票:0回答:1

我的数据框(df)由两列组成,一列包含随机值(连续测量),另一列包含三个级别(c1、c2、c3):

df <- data.frame(col1= round(rnorm(150),2),col2 =       c(rep("c1",times=50),rep("c2",times=50),rep("c3",times=50)))

我的 ggplot 代码看起来像这样:

library(ggplot2)

ggplot(df) +

geom_histogram(aes(x = col1, fill = col2),
             position = "stack",col="black", bins = 30, alpha = 0.6) +

scale_fill_manual(values = c("steelblue1", "yellow", "darkolivegreen2"),breaks = c("c1", "c2", "c3")) +

scale_fill_discrete("Factor", labels = c(expression(italic("c1")), 
                                         expression(italic("c2")),
                                         expression(italic("c3")))) +

theme_classic()

我在scale_fill_manual()中定义的颜色实际上并不对应于直方图中的颜色。看来这是两个参数scale_fill_manual()和scale_fill_discrete()的问题,因为它出现了这条消息:

填充比例已存在。 添加另一个比例进行填充,这将取代现有比例。

如何指定每个级别的颜色?

我已经尝试过这里已有的可能解决方案,但没有任何反应。

r ggplot2 colors scale fill
1个回答
0
投票

在香草

ggplot2
中,每种审美只能有一个比例,即添加
scale_fill_discrete
将覆盖(或删除)
scale_fill_manual
。但您可以简单地通过
scale_fill_manual
:

设置标签和/或名称

注意:如果您只想更改图例标签的字体,则无需使用

expression
。您可以使用
+ theme(legend.text = element_text(face = "italic"))
来完成此操作。

set.seed(123)

df <- data.frame(
  col1 = round(rnorm(150), 2),
  col2 = c(rep("c1", times = 50), rep("c2", times = 50), rep("c3", times = 50))
)

library(ggplot2)

ggplot(df) +
  geom_histogram(aes(x = col1, fill = col2),
    position = "stack", col = "black", bins = 30, alpha = 0.6
  ) +
  scale_fill_manual(
    values = c("steelblue1", "yellow", "darkolivegreen2"),
    breaks = c("c1", "c2", "c3"),
    labels = c(
      expression(italic("c1")),
      expression(italic("c2")),
      expression(italic("c3"))
    ),
    name = "Factor"
  ) +
  theme_classic()

© www.soinside.com 2019 - 2024. All rights reserved.