r - ggplot中的Quasiquotation问题
问题描述
为了简化项目报告,我创建了一个函数来干燥我的 ggplots。但是,我遇到了既有负面结果又有正面结果的条形图。我尝试编写一个 ifelse 语句来根据响应变量的值更改对齐方式,但我不断收到错误消息(错误:未为 quosures 定义基本运算符)。我在同一个语句中成功地取消了这个变量的引用。
library(tidyverse)
library(scales)
bar_chart_by_brand <- function(data,
response_var,
grouping_var,
title="",
subtitle="",
caption="",
ylab = "Index",
hline = 100,
round = 0,
percent = FALSE,
text_col = "white") {
response_var <- enquo(response_var)
grouping_var <- enquo(grouping_var)
p <- ggplot2::ggplot(data,
aes(x = fct_reorder(brand, !!response_var),
y = !!response_var,
fill = !!grouping_var)) +
geom_bar(stat = "identity", position = position_dodge()) +
geom_text(aes(label = ifelse(percent == TRUE,
scales::percent(!!response_var),
round(!!response_var, round))),
color = text_col,
fontface = "bold",
position = position_dodge(width = 1),
hjust = ifelse(!!response_var >= 0, 1, 0)) +
coord_flip() +
scale_fill_discrete() +
geom_hline(yintercept= hline, color = "#E32D40", alpha = 0.4) +
labs(title = title,
subtitle = subtitle,
caption = caption,
x = "Brand",
y = ylab) +
theme(
panel.grid.major = element_blank()
)
return(p)
}
set.seed(9929)
samp_set <- tibble(brand = sample(c("Alpha", "Beta", "Charlie"), size = 100, replace = TRUE), score = runif(100, min = -10, max = 10), segment = sample(c("Consumer", "Business"), size = 100, replace = TRUE))
samp_set %>%
group_by(brand, segment) %>%
summarise(rating = mean(score)) %>%
bar_chart_by_brand(., response_var = rating, grouping_var = segment, hline = mean(samp_set$score), text_col = "black", ylab = "Mean", round = 1)
解决方案
我想到了。我将 hjust 语句移到 aes 块中。奇迹般有效。
bar_chart_by_brand <- function(data,
response_var,
grouping_var,
title="",
subtitle="",
caption="",
ylab = "Index",
hline = 100,
round = 0,
percent = FALSE,
text_col = "white") {
response_var <- enquo(response_var)
grouping_var <- enquo(grouping_var)
p <- ggplot2::ggplot(data,
aes(x = fct_reorder(brand, !!response_var),
y = !!response_var,
fill = !!grouping_var)) +
geom_bar(stat = "identity", position = position_dodge()) +
geom_text(aes(label = ifelse(percent == TRUE,
scales::percent(!!response_var),
round(!!response_var, round)),
hjust = ifelse(!!response_var >= 0, 1, 0)),
color = text_col,
fontface = "bold",
position = position_dodge(width = 1)) +
coord_flip() +
scale_fill_discrete() +
geom_hline(yintercept= hline, color = "#E32D40", alpha = 0.4) +
theme_vincent() +
labs(title = title,
subtitle = subtitle,
caption = caption,
x = "Brand",
y = ylab) +
theme(
panel.grid.major = element_blank()
)
return(p)
}
推荐阅读
- mongodb - MongoDB大集合聚合很慢
- php - 如何使用会话改进一些 Symfony 代码
- symfony - 删除部分 url 并将其重定向到新的 url 而不会重叠旧的
- reactjs - 每次渲染都会出现 Highcharts 动画
- sql - 更新雪花中的行数限制
- python - 如何让 pymodbus 与 PLC 正确通信?
- csv - Static Highcharts graphic with csv data and dynamic footnote
- java - 带有 Edge Chromium 86/87 的 RemoteWebDriver 与 EdgeDriver.merge() 一起挂起
- reactjs - “从不”类型上不存在属性“setTabChange”。(React hooks Typescript) 使用 ref
- sql-server - 您可以在基于最终用户筛选器选择的查询时加入两个 SSAS 表吗?