如何阻止酒吧退出

问题描述 投票:1回答:1

说我使用以下代码创建条形图竞赛,该代码源于对这些问题的惊人答案-Animated sorted bar chart with bars overtaking each otherHow 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)

这将产生以下动画:

enter image description here

我不知道为什么当一个酒吧超过另一个酒吧时,它会向右伸出(甚至掩盖自己的标签)。为什么会发生这种情况,我该如何制止?我希望这些条能够顺利地相互超越,就像我在本文开头提到的问题中回答的那样。

r ggplot2 bar-chart gganimate
1个回答
0
投票
原因是它试图堆叠两个国家的条形图(简要地)重叠。

可以通过在position = "identity"上添加geom_colh()来解决:

geom_colh(aes(x=gdpPercap), position = "identity", width=0.9, alpha = 0.8, color = NA) +

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.