The facet_grid()
function in ggplot2 is very useful for visualizing multiple dependencies between variables. However sometimes, there is a limit to which it still makes sense to visualize the data as, for example, bar-plots and it may be better to just use a table.
Let´s assume I have visualized some data like this:
library(dplyr)
library(ggplot2)
set.seed(123)
cat1 <- as.character(sample(1:7, 1000, replace = T))
cat2 <- as.character(sample(1:9, 1000, replace = T))
cat3 <- as.character(sample(1:3, 1000, replace = T))
count <- sample(1:1000, 100, replace = T)
df <- data.frame(cat1, cat2, cat3, count)
df <- df %>%
group_by(cat1, cat2, cat3) %>%
summarise(count = sum(count)) %>%
mutate(share = count / sum(count) * 100)
ggplot(df, aes(cat1, share)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(round(df$share, 2), "\n(", df$count, ")")), size = 3) +
facet_grid(cat3 ~ cat2, scales = "free")
Now I have decided, that it makes more sense to just use a table. Is there a way to transform the visualization structure in this example into a table that uses the same category dependencies and contains the shares and counts in its cells?
Thanks for your suggestion.