Skip to content

[Request]: Create a single row stacked column chart ordered by value with "other" as last entry #9

Description

@Andrew-Saul

Existing topic?

No - New topic.

What is the topic?

plots

What is the example

library(tidyverse)

# data
tib <- tibble(
  cat_name = c("alpha", "beta", "omega", "other", "epsilon", "zeta"),
  value = sample(1:50, 6, replace = TRUE)
) %>%
  add_count(wt = value, name = "total") %>%
  mutate(prop = value / total)

# basic plot
tib %>%
  ggplot(aes(fill = cat_name, y = prop, x = "")) +
  geom_col() +
  coord_flip()

#####################################################################
# how to change order of categories from increasing to decreasing value, "other" at end
# align legend order with plot
# write absolute values in plot

# order categories excluding "other" according to descending value
revised_levels <- tib %>%
  arrange(value) %>%
  filter(cat_name != "other") %>%
  pull(cat_name)

# add "other" at end of vector
revised_levels <- append("other", revised_levels)

# desired output
# desc order of factors by value with "other" last
# percentage value overlay factor
# legend at bottom, 1 row and in order seen on plot

tib %>%
  mutate(cat_name = factor(cat_name, levels = revised_levels)) %>%
  ggplot(aes(fill = cat_name, y = prop, x = "")) +
  geom_col() +
  # geom_bar(position = "stack", stat = "identity")+
  coord_flip() +
  scale_y_continuous(
    name = "percentage",
    labels = scales::label_percent(accuracy = 1)
  ) +
  geom_text(
    aes(label = scales::percent(prop)),
    position = position_stack(vjust = 0.5),
    size = 5
  ) +
  theme(legend.position = "bottom") +
  guides(fill = guide_legend(
    title = NULL,
    nrow = 1,
    reverse = TRUE
  ))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions