簡體   English   中英

ggplot中的geom_bar-在兩個小節之間添加間隔/間隙

[英]geom_bar in ggplot - add a break / gap between two bars

我想在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")

在此處輸入圖片說明

...但是此圖有太多條形圖。

相反,我想簡單地繪制最低值的5條和最高值的5條,兩組柱之間有一個“間隙”,表明其他20條在中間,但已經帶走。

我不太確定geom_bar是否可以處理此問題,或者是否需要編輯數據框。 任何幫助,不勝感激!

使用facet_wrap怎么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"))

在此處輸入圖片說明

您可以通過調整面板之間的縫隙panel.spacingtheme


更新資料

還有一些額外的“主題”

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")

在此處輸入圖片說明

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")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM