说我使用以下代码创建条形图竞赛,该代码源于对这些问题的惊人答案-Animated sorted bar chart with bars overtaking each other和How to get rid of axis flickering caused by coord_flip when using gganimate and view_follow and geom_tile?:
library(gapminder)
library(gganimate)
library(tidyverse)
library(ggstance)
gap_smoother <- gapminder %>%
filter(continent == "Asia") %>%
group_by(country) %>%
complete(year = full_seq(year, 1)) %>%
mutate(gdpPercap = spline(x = year, y = gdpPercap, xout = year)$y) %>%
group_by(year) %>%
mutate(rank = min_rank(-gdpPercap) * 1) %>%
ungroup() %>%
group_by(country) %>%
complete(year = full_seq(year, .5)) %>%
mutate(gdpPercap = spline(x = year, y = gdpPercap, xout = year)$y) %>%
mutate(rank = approx(x = year, y = rank, xout = year)$y) %>%
ungroup() %>%
arrange(country,year) %>%
filter(year<=2007 & year>=1999) %>%
filter(rank<=8)
p <- ggplot(gap_smoother, aes(y=rank,
fill = as.factor(country), color = as.factor(country))) +
geom_colh(aes(x=gdpPercap), width=0.9, alpha = 0.8, color = NA) +
scale_y_reverse(labels = scales::comma) +
guides(color = FALSE, fill = FALSE) +
coord_cartesian(clip='off') +
theme(panel.background = element_rect(fill = "white")) +
geom_text(aes(x = 0, label = paste(country, " ")), vjust = 0.2, hjust = 1) +
geom_text(aes(x = gdpPercap,
label = scales::comma(round(gdpPercap), accuracy=1)), hjust = 0, nudge_x = 0 ) +
labs(title='{closest_state %>% as.numeric %>% floor}',
x = "GFP per capita", y = "") +
theme(plot.title = element_text(hjust = 0, size = 22),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
plot.margin = margin(1,1,1,4, "cm"),
axis.line.y = element_blank()) +
transition_states(year, transition_length = 1, state_length = 0) +
#enter_grow() +
#exit_shrink() +
ease_aes('linear')
animate(p, fps = 10, duration = 5, width = 600, height = 500)
#anim_save("output/bar.gif", p, end_pause=8, width = 600, height = 500, duration=5, nframes=50)
这将产生以下动画:
我不知道为什么当一个酒吧超过另一个酒吧时,它会向右伸出(甚至掩盖自己的标签)。为什么会发生这种情况,我该如何制止?我希望这些条能够顺利地相互超越,就像我在本文开头提到的问题中回答的那样。