从 tabyl table 改变值中制作 2-way 图 (ggplot2)

Making 2-way graph (ggplot2) out of a tabyl table changing values

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

如何使用 ggplot2 绘制这个由看门人构建的 table?问题是我想并排放置两个图:一个用于 dummy=TRUE,另一个用于 dummy=FALSE(但是更改标签,使 TRUE 被 a 替换,FALSE 被 b 替换——我遇到了困难这是因为 TRUE 和 FALSE 是合乎逻辑的)。我还想分别为 c 和 d 替换值 0 和 1。 非常感谢任何帮助。

你可以试试 tidyverse。诀窍是将数据从宽数据转换为长数据,因为这是 ggplot 的首选输入。这里我用的是pivot_longer,你也可以用reshape或者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())

使用基础R你可以试试

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