Home > OS >  R: Replace subplot created with facet_wrap
R: Replace subplot created with facet_wrap

Time:06-22

I have some data like this:

df <- tibble(
  key = c("v1", "v1", "v1", "v1", "v2", "v2", "v2", "v2", "v3"),
  values = c(1, 2, 4, 2, 5, 8, 3, 1, 0)
)

and create a histogram of each value:

plot <- df %>%
  ggplot(aes(x = values))  
    geom_histogram(aes(y = ..count..))  
    facet_wrap(~key, scales = "free", nrow = 1)

enter image description here

These values represent occurences of a specific observation. What I want is to replace a plot with some default text like "No data", if the histogram shows only one bar at x = 0, like it is the case in the third subplot. Is there a way to achieve this?

EDIT: Goal: enter image description here

CodePudding user response:

I'm not sure if this is what you wanted, but you may try

ver1

df %>%
  group_by(key) %>%
  mutate(values = values * ifelse(n() == 1, NA, 1),
         text = ifelse(n() ==1, "No \n observation \n available", NA)) %>%
  ggplot(aes(x = values))  
  geom_histogram(aes(y = ..count..))  
  geom_label(aes(label = text, y = 0.5, x = 1))  
  facet_wrap(~key, scales = "free", nrow = 1)

enter image description here

ver2

df %>%
  mutate(values = as.factor(values)) %>%
  group_by(key, values) %>%
  summarize(count = n()) %>%
  group_by(key) %>%
  mutate(count = count * ifelse(n() == 1, NA, 1),
         text = ifelse(n() ==1, "No \nobservation \n available", NA)) %>%
  ggplot(aes(x = values))  
  geom_col(aes(y = count))  
  geom_label(aes(label = text, y = 1))  
  facet_wrap(~key, scales = "free", nrow = 1)

enter image description here

CodePudding user response:

If "0" is not "NA", than I would plot it.

library(tidyverse)
df <- tibble(
  key = c("v1", "v1", "v1", "v1", "v2", "v2", "v2", "v2", "v3"),
  values = c(1, 2, 4, 2, 5, 8, 3, 1, 0)
) %>%
  mutate(key = factor(key, levels = c("v1", "v2", "v3")))

plot <- df %>%
  ggplot(aes(x = values, fill = key))  
  geom_bar(aes(y = ..count..))  
  facet_wrap(~ key)

plot

enter image description here

  • Related