Skip to content

gghighlight can't label every facet #146

@perlatex

Description

@perlatex
library(tidyverse)
library(gghighlight)
library(ggrepel)


# Suppose it's about cumulative number of papers published by four disciplines in 20 years for five schools

set.seed(2)

d <- tidyr::crossing(
    school = c("school1", "school2", "school3", "school4", "school5"),
    discipline = c("phys", "chem", "math", "art"),
    year = c(2000:2019)
) %>%
    group_by(school, discipline) %>%
    mutate(
        n_paper = cumsum(runif(20, 0, 100))
    ) %>%
    ungroup()


head(d)
#> # A tibble: 6 x 4
#>   school  discipline  year n_paper
#>   <chr>   <chr>      <int>   <dbl>
#> 1 school1 art         2000    18.5
#> 2 school1 art         2001    88.7
#> 3 school1 art         2002   146. 
#> 4 school1 art         2003   163. 
#> 5 school1 art         2004   257. 
#> 6 school1 art         2005   352.



# before gghighlight
highlight_school <- c("school1", "school3")

d1 <- d %>%
    group_by(school) %>%
    mutate(
        end_label = ifelse(year == max(year), school, NA_character_)
    ) %>%
    mutate(
        end_label = case_when(
            school %in% highlight_school ~ end_label,
            TRUE ~ NA_character_
        ),
        color_group = case_when(
            school %in% highlight_school ~ school,
            TRUE ~ "ZZOTHER"
        )
    ) %>%
    ungroup()



d1 %>%
    ggplot(aes(
        x = year, y = n_paper,
        color = color_group, label = end_label,
        group = school
    )) +
    geom_line(size = 0.8) +
    geom_text_repel(
        nudge_x = 1.1,
        nudge_y = 0.1,
        segment.color = NA
    ) +
    scale_color_manual(values = c("#195F90FF", "#D76500FF", "gray70")) +
    guides(color = FALSE) +
    facet_wrap(vars(discipline), scales = "free_x") +
    labs(
        x = NULL, y = NULL,
        title = "label for each facet"
    )
#> Warning: Removed 392 rows containing missing values (geom_text_repel).

Imgur

# use gghighlight

d %>%
    ggplot(aes(x = year, y = n_paper, color = school)) +
    geom_line() +
    facet_wrap(vars(discipline), scales = "free_x") +
    gghighlight(school %in% c("school1", "school3"),
                calculate_per_facet = TRUE,
                use_direct_label = TRUE,
                label_key = school,
                keep_scales = TRUE
    ) +
    labs(
        x = NULL, y = NULL,
        title = "how to add label for all facet?"
    )
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...

Imgur2

Created on 2020-04-11 by the reprex package (v0.3.0)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions