【发布时间】:2020-09-27 08:53:50
【问题描述】:
我正在创建一个绘图,并为它的数据准备创建了一个函数,该函数需要年份开始值和结束值作为函数的参数:
fn_gapminder_benchmark_diff <- function(year_start = 1952, year_end = 2007){
year_start = year_start
year_end = year_end
gapminder_joined %>%
filter(year %in% c(year_start,year_end)) %>%
arrange(country, year) %>%
group_by(country) %>%
mutate(benchmark_diff = benchmarked_india[2] - benchmarked_india[1],
max_pop = max(pop)) %>%
ungroup() %>%
arrange(benchmark_diff) %>%
filter(max_pop > 30000000) %>%
mutate(country = droplevels(country)) %>%
select(country, year, continent, benchmarked_india, benchmark_diff)
}
fn_gapminder_benchmark_diff(1987, 2007)
上面的函数在下面的代码中被调用
问题是我无法在图表的title 中使用上述函数arguments or variable values 来保持图表标题中的years 动态
# data function
fn_gapminder_benchmark_diff(1987, 2007) %>%
# data prep
mutate(country = fct_inorder(country)) %>%
group_by(country) %>%
mutate(benchmarked_end = benchmarked_india[2],
benchmarked_start = benchmarked_india[1] ) %>%
ungroup() %>%
# plotting
ggplot() +
geom_vline(xintercept = 0, col = "blue", alpha = 0.5) +
geom_label( label="India - As Benchamrking line", x=0, y="United States",
label.padding = unit(0.55, "lines"), # Rectangle size around label
label.size = 0.35, color = "black") +
geom_segment(aes(x = benchmarked_start, xend = benchmarked_end,
y = country, yend = country,
col = continent), alpha = 0.5, size = 7) +
geom_point(aes(x = benchmarked_india, y = country, col = continent), size = 9, alpha = .6) +
scale_color_brewer(palette = "Pastel2") +
labs(title = sprintf("GdpPerCapita Differenece with India (Starting point at %i and Ending at %i)",year_start, year_end),
subtitle = "Benchmarked India in blue line \nFor Countries with pop > 30000000 \n(Chart created by ViSa)",
col = "Continent", x = "GdpPerCap Difference at 1952 & 2007") +
# background & theme settings
theme_classic() +
theme(legend.position = "top",
axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank()
)
下面是我构建并尝试使其标题动态化的静态图表图像
【问题讨论】: