我的数据框(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()的问题,因为它出现了这条消息:
填充比例已存在。 添加另一个比例进行填充,这将取代现有比例。
如何指定每个级别的颜色?
我已经尝试过这里已有的可能解决方案,但没有任何反应。
在香草
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()