【问题标题】:Transform data visualization with ggplot and facet grid into a table使用 ggplot 和 facet grid 将数据可视化转换为表格
【发布时间】:2020-03-30 11:26:28
【问题描述】:

中的facet_grid() 函数对于可视化变量之间的多个依赖关系非常有用。然而,有时,将数据可视化为 仍然是有意义的限制,最好只使用表格。

假设我已经可视化了一些这样的数据:

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

现在我决定,只使用一张桌子更有意义。 有没有办法将此示例中的可视化结构转换为使用相同类别依赖关系并在其单元格中包含份额和计数的表格?

感谢您的建议。

【问题讨论】:

    标签: ggplot2 bar-plots r ggplot2 database-design facet-grid


    【解决方案1】:

    希望我回答正确,我猜你可以在ggpmisc 中使用geom_table(),首先你需要将表格嵌套在构面类别中:

    library(ggpmisc)
    library(tidyr)
    library(dplyr)
    library(ggplot2)
    
    df %>% 
    mutate(share=round(share,digits=3)) %>% 
    nest(data=c(cat1,count,share))
    # A tibble: 27 x 3
    # Groups:   cat2 [9]
       cat2  cat3            data
       <fct> <fct> <list<df[,3]>>
     1 1     1            [7 × 3]
     2 1     2            [7 × 3]
     3 1     3            [7 × 3]
     4 2     1            [7 × 3]
     5 2     2            [7 × 3]
     6 2     3            [7 × 3]
     7 3     1            [7 × 3]
     8 3     2            [7 × 3]
     9 3     3            [7 × 3]
    10 4     1            [7 × 3]
    

    我们可以绘制它:

    df %>% 
    mutate(share=round(share,digits=3)) %>% 
    nest(data=c(cat1,count,share)) %>% 
    ggplot() + geom_point(aes(x=0,y=0),color=NA) +
    geom_table(aes(x=0,y=0,label = data),
    vjust="middle",hjust="middle",size=2)+
    facet_grid(cat3 ~ cat2) + theme_void()
    

    您还可以查看 this discussionmanual 获取 ggpmisc。

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      相关资源
      最近更新 更多