Plotting two way bar chart using ggplot2

Viewed 137

I have the following randomly created data:

t<- matrix(sample.int(100,size=20,replace=TRUE),nrow=12,ncol=20)

a = list()
b = list()
for (x in (1:20) ) b[[x]] <- paste0("X_", x)  
for (x in (1:12) ) a[[x]] <- paste0("X", x)  

row.names(t) <- rbind(a)
colnames(t)  <- rbind(b)

t <- as.data.frame(t)

Here t is a hypothetical two way table of frequencies, I am trying to plot a graph like the one given here using ggplot2

I am not sure how can I make t in such a way that it can be used in ggplot2 code given in the link above. Also, I appreciate if you can provide suggestions on how to visualize a larger two way table, for instance, if dimension of t grows to something 30 x 50.

2 Answers

Here's one approach:

EDIT to show values underneath:

t %>%
  rownames_to_column() %>%
  pivot_longer(-rowname) %>%
  mutate(across(rowname:name, fct_inorder)) %>%
  ggplot(aes(x = 1, y = value)) + 
  geom_col() +
  geom_text(aes(x = 1, y = 0, label = value), vjust = 1.1, size = 2.5) +
  scale_x_continuous(breaks = NULL) +
  scale_y_continuous(breaks = NULL) +
  facet_grid(rowname~name) +
  coord_cartesian(clip = "off")

enter image description here

Here is a modification of Jon Springs code with some "layout" tweaking:

library(tidyverse)
df %>%
  rownames_to_column() %>%
  pivot_longer(-rowname) %>%
  mutate(across(rowname:name, fct_inorder)) %>%
  ggplot(aes(x = 1, y = value, fill=value)) + 
  geom_col(width = 0.5) +
  geom_text(aes(x = 1, y = 0, label = value), vjust = 1.1, size = 2.5) +
  scale_x_continuous(breaks = NULL) +
  scale_y_continuous(breaks = NULL) +
  facet_grid(rowname~name, switch = "both") +
  coord_cartesian(clip = "off") +
  theme_void() +
  theme(strip.background = element_blank(),
        strip.text.y.left = element_text(angle = 0),
        panel.spacing = unit(1, "lines"),
        strip.placement = "outside",
        strip.switch.pad.grid = unit(0.2, "in"))+
  guides(fill="none")

enter image description here

Related