在ggplot中找到N个唯一值 [英] Find N unique values inside ggplot
问题描述
我有一个示例数据框
df <- data.frame(a = c(sample(LETTERS[1:5], 10, TRUE), "Z", "Z"),
b = c(rnorm(10), NA, NA))
我正在尝试做一些简单的绘图并添加一些颜色。我可以很容易地做到这一点,而不必知道在绘制之前会有多少 a
个值:
and I'm trying to do some simple plotting and add some color. I can do this easily knowing how many a
values there will be before I even plot:
library(randomcoloR)
df %>%
filter(!is.na(b)) %>%
ggplot() +
geom_bar(aes(x = a, y = b),
fill = randomColor(5),
stat = "summary",
fun.y = "mean")
但是如果我不知道多少 a
会有价值吗?
But what if I don't know how many a
values there will be? How can get the number of unique a
inline inside the geom_xxx
statement?
使用 n_distinct(a)
不起作用并提供错误
Using n_distinct(a)
does not work and provides the error
df %>%
filter(!is.na(b)) %>%
ggplot() +
geom_bar(aes(x = a, y = b),
fill = randomColor(n_distinct(a)),
stat = "summary",
fun.y = "mean")
n_distinct_multi(list(...),na.rm)中的错误:对象'a 'not found
Error in n_distinct_multi(list(...), na.rm) : object 'a' not found
使用中的
不起作用并提供错误: uniqueN()
data.table
Using uniqueN()
from data.table
does not work and provides the error:
library(data.table)
df %>%
filter(!is.na(b)) %>%
ggplot() +
geom_bar(aes(x = a, y = b),
fill = randomColor(uniqueN(a)),
stat = "summary",
fun.y = "mean")
uniqueN(a)中的错误:找不到对象'a'
Error in uniqueN(a) : object 'a' not found
使用 unique(a)%>%length()
也不起作用,并且在上面提供了相同的错误。
Using unique(a) %>% length()
does not work, either, and provides the same error immediately above.
我可以在 geom_xxx
语句中内联唯一的 a
值的数量吗?我感觉好像在这里遗漏了一些明显的东西。
Can I find inline the number of unique a
values inside a geom_xxx
statement? I feel like I'm missing something obvious, here.
推荐答案
您可以将数据框传递给匿名函数:
You could pipe the data frame into an anonymous function:
df %>%
filter(!is.na(b)) %>%
(function(df) ({
ggplot(df) +
geom_bar(aes(x = a, y = b),
fill = randomColor(length(unique(df$a))),
stat = "summary",
fun.y = "mean")
}))
这篇关于在ggplot中找到N个唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!