Home > Enterprise >  Plotting two way bar chart using ggplot2
Plotting two way bar chart using ggplot2

Time:10-16

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 enter image description here

CodePudding user response:

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