sjPlot plot_xtab stack_view

47 views Asked by At

How can I avoid the %0 print for the following scenario ?

library(sjPlot)
library(palmerpenguins)
View(penguins)
plot_xtab(penguins$island, penguins$species, bar.pos = "stack",
margin = "row",  show.n = FALSE)

Penguin Species Distribution by Island

2

There are 2 answers

0
TarJae On

I did not find an argument to remove the 0% but I am quite sure that is possible. Here is a solution how we could get the same graph using tidyverse:

library(tidyverse)
library(palmerpenguins)

penguins %>%
  count(island, species) %>%
  group_by(island) %>%
  mutate(percentage = n / sum(n) * 100) %>%
  ggplot(aes(x = island, y = percentage, fill = fct_relevel(species, "Chinstrap", "Gentoo", "Adelie"))) +
  geom_bar(stat = "identity", width = 0.5) +
  geom_text(aes(label = scales::percent(percentage / 100)), position = position_stack(vjust = 0.5), size = 10) +
  labs(title = "Percentage of Species within Each Island",  x = "Island", y = "Percentage", fill = "species") +
  scale_y_continuous(labels = scales::percent_format(scale = 1)) +
  scale_fill_manual(values = c("#1f78b4", "#b2df8a",  "#a6cee3"))+
  theme_bw() +
  theme(text = element_text(size = 26))

enter image description here

0
stefan On

Besides creating the plot from scratch using ggplot2 as in the approach by @TarJae you could just add the value labels manually using a geom_text which allows to conditionally use an empty string a the label for zero counts.

library(sjPlot)
#> #refugeeswelcome
library(palmerpenguins)
library(ggplot2)

p <- plot_xtab(
  penguins$island, penguins$species,
  bar.pos = "stack",
  margin = "row", show.n = FALSE,
  show.values = FALSE
)

p +
  geom_text(
    aes(
      y = ypos,
      label = ifelse(
        prc > 0,
        sprintf("%.01f%%", 100 * .data$prc),
        ""
      )
    )
  )