【问题标题】:Sum variables in a dataframe and plot the sum in ggplot对数据框中的变量求和并在 ggplot 中绘制总和
【发布时间】:2018-11-12 01:03:30
【问题描述】:

我有一个数据框,其中包含调查对象现在和以前拥有的电视和收音机数量的数据:

DF <- data.frame(TV_now = as.numeric(c(4, 9, 1, 0, 4, NA)),
                 TV_before = as.numeric(c(4, 1, 2, 4, 5, 2)),
                 Radio_now = as.numeric(c(4, 5, 1, 5, 6, 9)),
                 Radio_before = as.numeric(c(6, 5, 3, 6, 7, 10)))

我想对每个变量的总值求和,然后创建一个条形图,显示调查对象现在和以前拥有的电视和收音机的数量。

我可以手动创建一个新数据框,其中仅包含原始 DF 中每个变量的值的总和

DFsum <- data.frame(TV_now = as.numeric(c(sum(DF$TV_now,na.rm = TRUE))),
                    TV_before = as.numeric(c(sum(DF$TV_before,na.rm = TRUE))),
                    Radio_now = as.numeric(c(sum(DF$TV_now,na.rm = TRUE))),
                    Radio_before = as.numeric(c(sum(DF$Radio_before,na.rm = TRUE))))

然后使用tidyr 执行以下操作:

library(tidyr)
library(ggplot2)
DFsum %>% 
  gather(key=Device, value=Number) %>% 
  ggplot(aes(x=Number,fill=Device)) + 
  geom_bar(aes(x = Device, y = Number), position = "dodge", stat = "identity")

这给了我想要的结果,但是对于应该容易实现的东西来说似乎不必要地复杂。有没有更简单的方法来绘制这个?

【问题讨论】:

  • c(4, 9, 1, 0, 4, NA) 这样的向量是数字,你不必在它们上使用as.numeric。您可能还对colSums 函数感兴趣。
  • 是否求和并不重要,因为 ggplot 无论如何都会堆叠类似填充的条:DF %&gt;% gather(Device, Number) %&gt;% drop_na(Number) %&gt;% ggplot(aes(Device, Number, fill = Device)) + geom_col(show.legend = FALSE)

标签: r ggplot2 tidyr


【解决方案1】:

您可以使用 dplyr::mutate_all 简化代码,因为您正在汇总所有列:

library(tidyverse)
library(ggplot2)

DF %>% mutate_all(funs(sum), na.rm = TRUE) %>%
  gather(key=Device, value=Number) %>% 
  ggplot(aes(x=Device,fill=Device)) + 
  geom_bar(aes(x = Device, y = Number), position = "dodge", stat = "identity")

【讨论】:

  • 优秀。这很有帮助。您知道为什么您的代码在 x 轴和 y 轴上都会导致“数字”吗?使用xlab("Device type") 很容易纠正,但还是有点小烦恼。
【解决方案2】:

简化数据创建。 R知道4、9、1等都是数字,你不需要as.numeric

DF <- data.frame(TV_now = c(4, 9, 1, 0, 4, NA),
                 TV_before = c(4, 1, 2, 4, 5, 2),
                 Radio_now = c(4, 5, 1, 5, 6, 9),
                 Radio_before = c(6, 5, 3, 6, 7, 10))

简化数据操作。先整理数据(将其转换为长格式),然后再做其他事情:

DF_long = gather(DF, key = "device") %>%
    group_by(device) %>%
    summarize(number = sum(value, na.rm = TRUE))

简化绘图。美学是继承的——您不需要多次指定它们。 geom_col 优先于 geom_barstat = "identity"。当每个 x 索引有一组时,position = "dodge" 什么都不做。

ggplot(aes(x = device, y = number, fill = device)) +
    geom_col()


我一般更喜欢自己做数据操作,但我们也可以依靠ggplots 堆叠条来代替求和,制作整个代码:

gather(DF, key = "device", value = "number") %>%
    ggplot(aes(x = device, y = number, fill = device)) +
    geom_col()

基本方法

dev = colSums(DF, na.rm = TRUE)
barplot(dev, col = factor(names(dev)))

【讨论】:

  • 这点很好。我们应该处理长格式的数据。
猜你喜欢
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
相关资源
最近更新 更多