如何阻止酒吧突出

How to stop bars from jutting out

假设我使用以下代码创建了一个条形图竞赛,该代码源自对这些问题的惊人答案 - and :

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)

这会产生以下动画:

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

原因是它试图在两个国家(短暂)重叠时堆叠它们。

可以通过将 position = "identity" 添加到您的 geom_colh():

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

结果: