英文:
how to change default color for the value not defined when we use scale_fill_manual
问题
我有一个如下所示的图表。由于我只关注于 name %in% c("A", "B", "C")
,我不会为其他名称定义颜色。默认情况下,它们被填充为深灰色。通过不为它们定义颜色,我能够绘制出 D 和 E,而不在图例中显示它们。
是否有一种方法可以将此默认颜色更改为浅灰色?如果可以,怎么做?
# 载入 ggplot2
library(ggplot2)
# 创建数据
data <- data.frame(
name=c("A","B","C","D","E"),
value=c(3,12,5,18,45)
)
# 条形图
ggplot(data, aes(x=name, y=value, fill=name)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values = c("A"="red", "B"="green", "C"="blue") )
英文:
I have a plot like below. As I am only focusing on name %in% c("A", "B", "C")
, I will not define the color for other names. By default, they were filled with dark grey. By not defining the color for those, I was able to plot D, E out without showing them in the legend.
Is it a way I can change this default color to light grey? If so , how?
# Load ggplot2
library(ggplot2)
# Create data
data <- data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# Barplot
ggplot(data, aes(x=name, y=value, fill=name)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values = c("A"="red", "B"="green", "C"="blue") )
答案1
得分: 2
你可以使用参数na.value
来将默认颜色更改为浅灰色,像这样:
# 载入 ggplot2
library(ggplot2)
# 创建数据
data <- data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# 条形图
ggplot(data, aes(x=name, y=value, fill=name)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values = c("A"="red", "B"="green", "C"="blue"),
na.value = "lightgrey")
创建于2023-05-10,使用 reprex v2.0.2
英文:
You could use the argument na.value
to change the default color to light grey like this:
# Load ggplot2
library(ggplot2)
# Create data
data <- data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# Barplot
ggplot(data, aes(x=name, y=value, fill=name)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values = c("A"="red", "B"="green", "C"="blue"),
na.value = "lightgrey")
<!-- -->
<sup>Created on 2023-05-10 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论