有没有办法在同一管道中使用ggplot2中scale_x_continuous()中用dplyr计算的列?
p2 <- chat %>%
count(author) %>%
ggplot(aes(x = reorder(author, n), y = n, fill = n)) +
geom_bar(stat = "identity") +
coord_flip() +
theme_classic() +
scale_fill_viridis() +
scale_x_continuous(breaks = seq(0, **max(n)**, by = 250))
theme(
axis.title.x = element_blank(), axis.title.y = element_blank(),
legend.position = "none",
plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
plot.subtitle = element_text(color = '#666664', size = 10, hjust = 0.5))
基本上,我是在计算其他作者(因子列)出现在数据框中的次数。但是,R不允许我在scale_x_continuous中使用n
(即count()返回的列的名称)。但这确实在ggplot()函数中。
有办法吗?还是我被迫做类似的事情:
data <- chat %>%
count(author)
p2 <- ggplot(data, aes(x = reorder(author, n), y = n, fill = n)) +
geom_bar(stat = "identity") +
coord_flip() +
theme_classic() +
scale_fill_viridis() +
scale_x_continuous(breaks = seq(0, **max(data$n)**, by = 250))
theme(
axis.title.x = element_blank(), axis.title.y = element_blank(),
legend.position = "none",
plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
plot.subtitle = element_text(color = '#666664', size = 10, hjust = 0.5))
谢谢!
答案 0 :(得分:3)
您可以使用花括号和点表示法(this question和here中接受的答案的最后一部分中的相关信息):
library(tidyverse)
library(viridis)
#> Loading required package: viridisLite
p2 <- iris %>%
sample_n(100) %>%
count(Species) %>%
{
ggplot(., aes(x = reorder(Species, n), y = n, fill = n)) +
geom_bar(stat = "identity") +
coord_flip() +
theme_classic() +
scale_fill_viridis() +
scale_y_continuous(breaks = seq(0, max(.$n), by = 20)) +
theme(
axis.title.x = element_blank(), axis.title.y = element_blank(),
legend.position = "none",
plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
plot.subtitle = element_text(color = '#666664', size = 10, hjust = 0.5)
)
}
p2
由reprex package(v0.3.0)于2019-11-24创建
请注意,您没有提供任何可复制的示例,因此我以iris
为起点,并进行了一些行采样以获取不同的物种计数频率。如果您用reproducible example更新问题,我将更新答案。