R 对数据帧中的变量求和,并在ggplot中绘制和

R 对数据帧中的变量求和,并在ggplot中绘制和,r,ggplot2,tidyr,R,Ggplot2,Tidyr,我有一个数据框,其中包含调查对象现在和以前拥有的电视和收音机数量的数据: 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_bef

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

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

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

您可以使用
dplyr::mutate\u 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")

简化数据创建。R知道4、9、1等是数字,您不需要将
作为.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))
简化绘图。美学是继承的-您不需要多次指定它们<使用
stat=“identity”
时,code>geom\u col
优于
geom\u bar
position=“dodge”
在每个x索引有一个组时不执行任何操作

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


我通常更喜欢自己处理数据,但我们也可以依靠
ggplot
s堆叠条来代替求和,使整个代码:

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

c(4,9,1,0,4,NA)
这样的向量是数值的,您不必在它们上面使用
as.numeric
。您可能还对
colSums
函数感兴趣。求和并不重要,因为ggplot将堆叠类似填充的条:
DF%%>%gather(Device,Number)%%>%drop_na(Number)%%>%ggplot(aes(Device,Number,fill=Device))+geom\u col(show.legend=FALSE)
非常好。这很有帮助。你知道为什么你的代码在x轴和y轴上都有“数字”吗?使用
xlab(“设备类型”)
很容易纠正,但还是有点麻烦。这是一个很好的观点。我们应该处理长格式的数据。
ggplot(aes(x = device, y = number, fill = device)) +
    geom_col()
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)))