我在 ggplot 中创建了一个看起来不错的图形...
pollinators_1 <- ggplot(data = pollinator_counts_hybrids, aes(x = pollinator.species, y = n, fill = taxa.visited)) +
geom_bar(stat = 'identity') +
facet_wrap(~ site, ncol = 1) +
theme_classic() +
labs(title = "Pollinators of Gentian taxa at sites with hybrids present", x = "Pollinator Species", y = "Number of Visits", fill = "Taxa")
pollinators_2 <- pollinators_1 + scale_fill_manual('Taxa', values=c('#a1d99b', '#9ebcda', '#8856a755'))
pollinators_3 <- pollinators_2 + theme(axis.text.x = element_text(angle = 45, hjust = 1))
我想在每个facet_wrapped图中有一些该图独有的文本。我拿了这段代码:
dat_text <- data.frame(
label = c("4 cylinders", "6 cylinders", "8 cylinders"),
cyl = c(4, 6, 8)
)
p + geom_text(
data = dat_text,
mapping = aes(x = -Inf, y = -Inf, label = label),
hjust = -0.1,
vjust = -1
)
来自过去的 StackOverflow 问题:在 ggplot2 中的各个方面注释文本并将其写入我自己的代码:
text_pollinator_A <- data.frame(label = c("n = 11", "n = 15", "n = 10", "n = 10"),
site = c("BS", "LHF", "SHP", "SPN"))
pollinators_4 <- pollinators_3 + geom_text(data = text_pollinator_A, mapping = aes(x = -Inf, y = -Inf, label = label),
hjust = -0.1,
vjust = -1)
但是我收到错误:
> pollinators_4
Error in `geom_text()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error:
! object 'taxa.visited' not found
Run `rlang::last_trace()` to see where the error occurred.
如果有人能帮我解决这个问题,那就太好了!谢谢!
您只希望
fill
在栏上起作用,而不是在文本上起作用。因此,将 aes(fill)
从全局 ggplot()
调用中移出,并将其移至 geom_bar()
层。这是更正后的代码:
pollinators_1 <- ggplot(data = pollinator_counts_hybrids,
aes(x = pollinator.species, y = n)) +
geom_bar(stat = 'identity',aes(fill=taxa.visited)) +
facet_wrap(~ site, ncol = 1) +
theme_classic() +
labs(title = "Pollinators of Gentian taxa at sites with hybrids present",
x = "Pollinator Species", y = "Number of Visits", fill = "Taxa")
pollinators_2 <- pollinators_1 + scale_fill_manual('Taxa',
values=c('#a1d99b', '#9ebcda', '#8856a755'))
pollinators_3 <- pollinators_2 + theme(axis.text.x = element_text(angle = 45, hjust = 1))
text_pollinator_A <- data.frame(label = c("n = 11", "n = 15", "n = 10", "n = 10"),
site = c("BS", "LHF", "SHP", "SPN"))
pollinators_4 <- pollinators_3 + geom_text(data = text_pollinator_A,
mapping = aes(x = -Inf, y = -Inf, label = label),
hjust = -0.1,
vjust = -1)