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