ggplot中的geom_bar-在两个小节之间添加间隔/间隙

时间:2018-09-18 00:44:42

标签: r ggplot2

我想在R中制作一个条形图,其中两组条形之间有间隙(但不是一组条形图)。我这里有30个篮球队的数据及其平均得分:

dput(mydf)
structure(list(thisTeamAbb = c("ATL", "BKN", "BOS", "CHA", "CHI", 
"CLE", "DAL", "DEN", "DET", "GSW", "HOU", "IND", "LAC", "LAL", 
"MEM", "MIA", "MIL", "MIN", "NOP", "NYK", "OKC", "ORL", "PHI", 
"PHX", "POR", "SAC", "SAS", "TOR", "UTA", "WAS"), pts = c(1.197, 
1.138, 1.016, 1.127, 1.196, 1.144, 1.21, 1.197, 1.155, 1.107, 
1.126, 1.138, 1.282, 1.105, 1.096, 1.205, 1.121, 1.125, 1.205, 
1.208, 1.208, 1.098, 1.056, 1.167, 1.039, 1.128, 0.99, 1.171, 
0.987, 1.127)), row.names = c(NA, -30L), class = c("tbl_df", 
"tbl", "data.frame"))

> head(mydf)
# A tibble: 6 x 2
  thisTeamAbb   pts
  <chr>       <dbl>
1 ATL          1.20
2 BKN          1.14
3 BOS          1.02
4 CHA          1.13
5 CHI          1.20
6 CLE          1.14

有了它,我就能绘制出30个柱形图,并且柱形图的排序越来越多:

mydf %>% ggplot() + 
  geom_bar(aes(x = reorder(thisTeamAbb, pts), y = pts), stat = "identity")

enter image description here

...但是此图的条形太多。

相反,我想简单地绘制最低值的5条和最高值的5条,两组条之间有一个“间隙”,表明其他20条在中间但已被取出。

我不太确定geom_bar是否可以处理此问题,或者是否需要编辑数据框。任何帮助,不胜感激!

2 个答案:

答案 0 :(得分:2)

如何使用facet_wrap

df %>%
    mutate(region = case_when(
        min_rank(desc(pts)) <= 5 ~ "high",
        min_rank(pts) <= 5 ~ "low",
        TRUE ~ "middle")) %>%
    filter(region %in% c("low", "high")) %>%
    mutate(
        thisTeamAbb = reorder(thisTeamAbb, pts),
        region = factor(region, c("low", "high"))) %>%
    ggplot() +
    geom_col(aes(thisTeamAbb, pts)) +
    facet_wrap(~ region, scale = "free_x") +
    theme(panel.spacing = unit(2, "lines"))

enter image description here

您可以通过panel.spacing内的theme来调整面板之间的间距。


更新

还有一些额外的“主题”

df %>%
    mutate(region = case_when(
        min_rank(desc(pts)) <= 5 ~ "high",
        min_rank(pts) <= 5 ~ "low",
        TRUE ~ "middle")) %>%
    filter(region %in% c("low", "high")) %>%
    mutate(
        thisTeamAbb = reorder(thisTeamAbb, pts),
        region = factor(region, c("low", "high"))) %>%
    ggplot() +
    geom_col(aes(thisTeamAbb, pts)) +
    facet_wrap(~ region, scale = "free_x", strip.position = "bottom") +
    theme_minimal() +
    theme(
        panel.spacing = unit(5, "lines"),
        strip.placement = "outside")

enter image description here

答案 1 :(得分:2)

library(tidyverse)

my_df2 %>%
  mutate(rank = <-
  bind_rows(
    my_df %>% top_n(wt = pts, 5),
    my_df %>% slice(1) %>% mutate(thisTeamAbb = "Middle 20", pts = NA_real_),
    my_df %>% top_n(wt = pts, -5)  # Includes 6 b/c ties....
) %>%
# Here I make the team name into sorted factor, with Middle 20 in the middle
mutate(thisTeamAbb = thisTeamAbb %>% 
           fct_reorder(pts) %>%
           fct_relevel("Middle 20", after = 5))

my_df2 %>% ggplot() + 
  geom_bar(aes(x = thisTeamAbb, y = pts), stat = "identity")

enter image description here