【问题标题】:Create side-by-side bar chart from dplyr summarise() data [R]从 dplyr summarise() 数据创建并排条形图 [R]
【发布时间】:2018-09-13 16:50:24
【问题描述】:

我正在尝试通过对此数据集进行一些探索性数据分析来学习 R:https://www.cdc.gov/brfss/。这个想法是同时使用 dplyrggplot2

我有以下代码:

brfss2013 %>%
  filter(!is.na(menthlth), !is.na(veteran3)) %>%
  group_by(menthlth) %>%
  summarise(vcount = sum(veteran3 == "Yes"), nvcount = sum(veteran3 == "No"))

我想创建一个并排的条形图,其中 x 轴显示从 0 到 30(第 30 个)的数字,y 轴显示左侧的 vcount 和右侧的 nvcount(对于每个值薄荷)。我知道我可以将代码的最后一行链接到 ggplot 行,但我不明白如何创建并排图表。

我尝试将 summarise 的输出分配给一个变量,以便我可以使用 melt 命令或类似命令,但这会导致错误 ("找不到对象'veteran3'”)。有没有更简单的方法可以直接并排绘制两个变量?

感谢您的帮助,如果我遗漏了一些明显的东西,我们深表歉意。

编辑:我现在将结果分配给变量adput(head(a, 10)) 给出了

structure(list(menthlth = 0:9, vcount = c(46931L, 1221L, 1861L, 1083L, 545L, 1323L, 197L, 466L, 105L, 22L), nvcount = c(287025L, 13964L, 21633L, 12505L, 6111L, 15312L, 1664L, 5882L, 1139L, 175L)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame" ))

【问题讨论】:

  • 嗨。如果您可以dput(head(your data, 10)) 会有所帮助,这将极大地帮助您处理数据。
  • 就像您正常使用管道一样。 ... %>% dput(head(., 10)) 或为其指定名称。反正可能会更好
  • 你需要melt/gather你的数据:看这个possible duplicate;或this one
  • 只需使用您在上面向我们展示的整个代码并将a<-放在前面
  • 这有点令人困惑,但要分配管道操作的结果,您将赋值运算符放在整个链之前。所以:a <- df %>% filter(...) %>% mutate(...) 将运行整个管道并将最终结果分配给变量 a

标签: r ggplot2 dplyr


【解决方案1】:
library(tidyverse)
# dat_ <- structure(list(menthlth = 0:9, vcount = c(46931L, 1221L, 1861L, 1083L, 545L, 1323L, 197L, 466L, 105L, 22L), nvcount = c(287025L, 13964L, 21633L, 12505L, 6111L, 15312L, 1664L, 5882L, 1139L, 175L)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame" ))

plot_dat <- dat_ %>% gather(group,y, 2:3) # reshape your data frame for plotting - 

ggplot()+ 
  geom_col(data = plot_dat, 
           aes(as.character(menthlth), y, fill = group),
           position = position_dodge())

您应该使您的 x 离散 (as.character(menthlth))。并使用position = position_dodge(),因为列是堆叠的(尝试省略它)

【讨论】:

    【解决方案2】:

    我无权访问您的数据,但根据您的示例,我制作了以下数据集:

    dt<-data.frame(menthlth=sample( c(1:10),10),
                   vcount=sample( c(1:1000),10),
                   nvcount=sample( c(1:1000),10))
    

    您需要先修改数据集的结构:

    NewDT<- data.frame(menthlth= dt$menthlth,
                      category=c(rep("vcount",length(dt$menthlth)),rep("nvcount",length(dt$menthlth) )),
                        value=c(dt$vcount,dt$nvcount)) 
    

    然后他们制作条形图:

    library(ggplot2)
    
    ggplot(data=NewDT, aes(x=menthlth, y=value, fill=category)) +
      geom_bar(stat="identity", position=position_dodge())
    

    结果是:

    【讨论】:

    • 感谢您的回答。由于@Tjebo 的回答有效,我最终没有使用它,但还是谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多