Home > Software design >  Making 2-way graph (ggplot2) out of a tabyl table changing values
Making 2-way graph (ggplot2) out of a tabyl table changing values

Time:02-17

male FALSE  TRUE
    0 50.0% 66.7%
    1 50.0% 33.3%

structure(list(male = 0:1, `FALSE` = c("50.0%", "50.0%"), `TRUE` = c("66.7%", 
"33.3%")), row.names = c(NA, -2L), core = structure(list(male = 0:1, 
    `FALSE` = c(1, 1), `TRUE` = c(4, 2)), class = "data.frame", row.names = c(NA, 
-2L)), tabyl_type = "two_way", var_names = list(row = "male", 
    col = "dummy"), class = c("tabyl", "data.frame"))

How can I make a plot using ggplot2 of this table constructed with janitor? The thing is that I would like two plots side-by-side: one for dummy=TRUE and the other for dummy=FALSE (but changing the labels such that TRUE is replaced by a and FALSE by b -- i am having difficulties with this because TRUE and FALSE are logical). I would also like to replace the values 0 and 1 for c and d respectively. Any help is deeply appreciated.

CodePudding user response:

You can try a tidyverse. The trick is to transform the data from wide to long since this is the prefered input for ggplot. Here I used pivot_longer, but you can also use reshape or melt.

library(tidyverse)
df %>% 
  pivot_longer(-1) %>% 
  mutate(name = ifelse(name, "a", "b")) %>% 
ggplot( aes(factor(male), value, fill =name))   
   geom_col(position = position_dodge())

enter image description here

Using base R you can try

# transform percentages to numerics
df$a <- as.numeric(gsub("%", "", df$`TRUE`))
df$b <- as.numeric(gsub("%", "", df$`FALSE`))
barplot(cbind(a, b) ~ male, df, beside=T,legend.text = TRUE)

enter image description here

  • Related