为了简化项目报告,我创建了一个函数,用于干燥ggplots。但是,我在条形图上遇到麻烦,这些条形图既有正面结果,也有负面结果。我试图编写一个ifelse语句来根据响应变量的值更改对齐方式,但是我不断收到错误消息(错误:未为基数定义基运算符)。我在同一条语句中成功取消了对该变量的引用。
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)
答案 0 :(得分:0)
我知道了。我将hjust语句移到es块中。就像魅力一样。
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)
}