我如何自动调整geom_bar图的所需颜色数量?

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

我想使用ggplot为具有不同颜色条形的列制作条形图。

library(ggplot2)

set.seed(123)

df_a <- data.frame(A1 = sample(c(0, 1, 2, 3, 4), 10, replace = TRUE))

ggplot(df_a, aes(A1)) +
  geom_bar(fill = c("green", "blue", "red", "yellow", "black"))  +
  scale_x_discrete(drop = FALSE)

效果很好:enter image description here但是,在这么小的样本中,我不能指望所有可能的数字都存在。这是一个例子,就是这种情况:

set.seed(321)

df_a <- data.frame(A1 = sample(c(0, 1, 2, 3, 4), 10, replace = TRUE))

使用之前的ggplot ...

ggplot(df_a, aes(A1)) +
  geom_bar(fill = c("green", "blue", "red", "yellow", "black"))  +
  scale_x_discrete(drop = FALSE)

...引发错误:

Error: Aesthetics must be either length 1 or the same as the data (3): fill

[似乎,由于要填充3个小节,所以期望矢量正好具有3种颜色?

为什么?

是否有一种无需先检查数字即可填写的方法?

并强制使用预定义数量的小节(即使是空的?)>

编辑:

AndS提出了一个解决方案。

set.seed(321)

df_a <- data.frame(A1 = sample(c(0, 1, 2, 3, 4), 10, replace = TRUE))

ggplot(df_a, aes(A1)) +
  geom_bar(aes(fill = as.factor(A1)))  +
  scale_x_discrete(drop = FALSE)

在这种情况下,将导致4个小节(包括1个空小节)。

但是,要获得全部5条(包括缺失的条),必须标记数据:

set.seed(321)

df_a <- data.frame(A1 = sample(c(0, 1, 2, 3, 4), 10, replace = TRUE))

df_a[[1]] <- ordered(df_a[[1]], levels = c(0:4), labels = c(0, 1, 2, 3, 4))

ggplot(df_a, aes(A1)) +
  geom_bar(aes(fill = as.factor(A1)))  +
  scale_x_discrete(drop = FALSE)

是否有避免这种情况的方法?

我想使用ggplot为具有不同颜色条形的列制作条形图。 library(ggplot2)set.seed(123)df_a

r ggplot2 bar-chart fill geom-bar
1个回答
0
投票

aes()geom_bar调用内或外部提供fill参数之间存在区别。您收到的错误消息是很不言自明的:

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