R语言 使用基表功能时,如何将列联表直接转换为条形图?

5sxhfpxr  于 2023-02-26  发布在  其他
关注(0)|答案(2)|浏览(218)

第一节第一节第一节第一节第一次

我试图直接从列联表创建一个条形图,但我不知道ggplot 2中有这样的功能,我的原始数据看起来像这样,列中的0、1和-1代表分类答案,问题是我不知道如何根据每个列中的唯一值对它们进行分组。
我正在使用这段代码在列之间迭代,这是我到目前为止所拥有的。
for(列名中的x(df)){
条形图〈- ggplot(df,aes(x =变量,y=x,填充= dfx))+几何条形图(状态=“标识”,位置=“减淡”)
}

dgtucam1

dgtucam11#

您可能希望创建一个单独的表。将图例提取为单独的grob,然后单独布局每个部分。
样本代码:

library(grid)
    library(gridExtra)
    library(ggplot2)

  df1<-df %>%
      gather(name, value, `Yes`:`No`)   
    
    df1$name=factor(df1$name, levels=c("Yes", "No"))
      
      g_legend <- function(a.gplot){
        tmp <- ggplot_gtable(ggplot_build(a.gplot))
        leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
        legend <- tmp$grobs[[leg]]
        return(legend)}
    
    p = ggplot(df1, aes(x=variable, y=value, fill=name) ) + 
      geom_bar(stat="identity", position="dodge")+ 
      theme_bw()+
      theme(axis.text.x = element_text(hjust = 1, face="bold", size=12, color="black"), 
            axis.title.x = element_blank(),
            axis.text.y = element_text( face="bold", size=12, color="black"),
            axis.title.y = element_blank(),
            strip.text = element_text(size=10, face="bold"),
            legend.position = "none",
            legend.title = element_blank(),
            legend.text = element_text(color = "black", size = 16,face="bold"))+
            scale_y_continuous(expand = expansion(mult = c(0, .1)))+
    ggtitle("Relationship between daily consumption of fruit/fruit juice and SNP AX")
    
    
    
    leg = g_legend(p)
    
    
    tab = t(df)
    tab = tableGrob(tab, rows=NULL, theme=ttheme_minimal(base_size = 16))
    tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")
    
    grid.arrange(arrangeGrob(nullGrob(), 
                             p +  
                               theme(axis.text.x=element_blank(),
                                     axis.title.x=element_blank(),
                                     axis.ticks.x=element_blank()),
                             widths=c(1,8)), 
                arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
                                                    tab, nullGrob(), widths=c(6,20,1)), heights=c(4,1))

情节:


样品数据:

df<-structure(list(variable = c("AA", "AB", "BB"), Yes = c(10, 50, 
90), No = c(80, 40, 10)), spec = structure(list(cols = list(variable = structure(list(), class = c("collector_character", 
"collector")), Yes = structure(list(), class = c("collector_double", 
"collector")), No = structure(list(), class = c("collector_double", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), row.names = c(NA, 
-3L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))

df1<-structure(list(variable = c("AA", "AB", "BB", "AA", "AB", "BB"
), name = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Yes", 
"No"), class = "factor"), value = c(10, 50, 90, 80, 40, 10)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
bogh5gae

bogh5gae2#

上一个答案建议如何在列联表之上构建条形图,这里我建议如何从列联表构建条形图。
推荐的工作流程是基于整洁的数据构建列联表和图,下面是一个例子:

# [Case A] Both the contingency table and the plot are based on tidy data

# Data
df <- data.frame(variant = c(rep("AA", times = 10),
                             rep("AA", times = 80),
                             rep("AB", times = 50),
                             rep("AB", times = 40),
                             rep("BB", times = 90),
                             rep("BB", times = 10)),
                 fruit_daily = c(rep("yes", times = 10),
                                 rep("no", times = 80),
                                 rep("yes", times = 50),
                                 rep("no", times = 40),
                                 rep("yes", times = 90),
                                 rep("no", times = 10)))

# Contingency table
df |> 
  janitor::tabyl(fruit_daily, variant) 

# Bar plot (using relevel to maintain the bars ordered as in the question)
df |> 
  dplyr::mutate(fruit_daily = forcats::fct_relevel(fruit_daily, "yes", "no")) |>
  ggplot2::ggplot(aes(fill = fruit_daily, x = variant)) +
  geom_bar(position = position_dodge())

然而,您 * 可以 * 从列联表开始构建条形图:

# [Case B] A bar plot from the contingency table using janitor::tabyl
df |> 
  janitor::tabyl(variant, fruit_daily) |>
  tidyr::gather(key = answers, value = how_many, no:yes) |>
  dplyr::mutate(answers = forcats::fct_relevel(answers, "yes", "no")) |>
  ggplot2::ggplot(aes(y = how_many, x = variant, fill = answers)) +
  geom_col(position = position_dodge())

最后,从基表函数(受this solution启发)开始执行相同的任务:

# [Case C] A bar plot from the contingency table using base table function
as.data.frame(table(df)) |>  
  dplyr::mutate(fruit_daily = forcats::fct_relevel(fruit_daily, "yes", "no")) |>
  ggplot2::ggplot(aes(y = Freq, x = variant, fill = fruit_daily)) +
  geom_col(position = position_dodge())

相关问题