如何在使用scale_fill_manual时更改未定义值的默认颜色。

huangapple go评论73阅读模式
英文:

how to change default color for the value not defined when we use scale_fill_manual

问题

我有一个如下所示的图表。由于我只关注于 name %in% c("A", "B", "C"),我不会为其他名称定义颜色。默认情况下,它们被填充为深灰色。通过不为它们定义颜色,我能够绘制出 D 和 E,而不在图例中显示它们。

是否有一种方法可以将此默认颜色更改为浅灰色?如果可以,怎么做?

如何在使用scale_fill_manual时更改未定义值的默认颜色。

# 载入 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(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;) , 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?

如何在使用scale_fill_manual时更改未定义值的默认颜色。

# Load ggplot2
library(ggplot2)

# Create data
data &lt;- data.frame(
  name=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;) ,  
  value=c(3,12,5,18,45)
  )

# Barplot
ggplot(data, aes(x=name, y=value, fill=name)) + 
  geom_bar(stat = &quot;identity&quot;)   +
  scale_fill_manual(
    values = c(&quot;A&quot;=&quot;red&quot;, &quot;B&quot;=&quot;green&quot;, &quot;C&quot;=&quot;blue&quot;) )

答案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")

如何在使用scale_fill_manual时更改未定义值的默认颜色。

创建于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 &lt;- data.frame(
  name=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;) ,  
  value=c(3,12,5,18,45)
)

# Barplot
ggplot(data, aes(x=name, y=value, fill=name)) + 
  geom_bar(stat = &quot;identity&quot;)   +
  scale_fill_manual(
    values = c(&quot;A&quot;=&quot;red&quot;, &quot;B&quot;=&quot;green&quot;, &quot;C&quot;=&quot;blue&quot;), 
    na.value = &quot;lightgrey&quot;)

如何在使用scale_fill_manual时更改未定义值的默认颜色。<!-- -->

<sup>Created on 2023-05-10 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年5月11日 01:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定