Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 绘制ggplot中字段的总和_R_Ggplot2 - Fatal编程技术网

R 绘制ggplot中字段的总和

R 绘制ggplot中字段的总和,r,ggplot2,R,Ggplot2,我有以下用于绘制一系列数字列之和的代码。这将返回一个堆叠条形图,其中每列的贡献是不同的颜色 library(readxl) library(tidyverse) library(ggthemes) library(extrafont) library(RColorBrewer) library(scales) library(gridExtra) ggplot(data, aes(x = `Location Group`, y = Medical + Wag

我有以下用于绘制一系列数字列之和的代码。这将返回一个堆叠条形图,其中每列的贡献是不同的颜色

library(readxl)
library(tidyverse)
library(ggthemes)
library(extrafont)
library(RColorBrewer)
library(scales)
library(gridExtra)

ggplot(data, aes(x = `Location Group`, 
                 y = Medical + Wages + `Rehab Cum` + `Invest Cum`,
                 fill = variable)) +
  geom_bar(stat = "identity")
这是在FUN(X[[i]],…)中出现的错误
错误:找不到对象“variable”

我不确定是什么原因导致了这种情况,格式可以很容易地从100个其他案例中复制和粘贴。在发生冲突的情况下包括库(但我怀疑情况是否如此)

样本数据将是

Medical Wages `Rehab Cum` `Invest Cum`
    <dbl> <dbl>       <dbl>        <dbl>
1    1230 10360        1234          200
2     245  9782        2345          300
3    2234  6542        3456            0
4    5564  1234        4567          400
5      13   357           0            0
6     987   951           0            0
医疗工资`康复和``投资和`
1    1230 10360        1234          200
2     245  9782        2345          300
3    2234  6542        3456            0
4    5564  1234        4567          400
5      13   357           0            0
6     987   951           0            0

问题在于ggplot2不理解变量是什么。ggplot2的关键在于记住,绘图的每个方面都应该由数据中的一列表示

因此,在这种情况下,不需要为映射赋予四个不同的列,如果变量彼此重叠,ggplot2将自动堆叠变量(
geom_bar
具有默认的
position=“stack”
)。相反,您希望在数据中有一列表示
y
值,另一列表示条形图每个部分应具有的颜色(
fill

使用
fill=variable
是正确的:您希望根据绘制的变量对条形图进行着色。但是
variable
实际上需要是数据集中的一列。所以你希望它看起来更像这样:

`Location Group`        variable        value
---------------------------------------------
location1               Medical         20
location1               Wages           30
location1               Rehab Cum       45
location1               Invest Cum      60
location2               Medical          5
location2               Wages           15
location2               Rehab Cum       55
location2               Invest Cum      90
然后将
x
映射到
位置组
y
映射到
填充
映射到
变量

您可以使用以下方法将数据放入此形状:


您的
数据
变量是什么?你能发布一组最小的数据来重现问题吗?用样本数据更新OP。它们只是数字,它也有专栏,让问题更清楚。这将使其他人更容易从中学习。这几乎做到了。我唯一需要做的更改是将第一行存储为变量,然后将其输入第二行。谢谢哎哟,是的,我刚开始的时候没打算重新输入绘图代码
library(tidyr)
data = data %>% gather(variable, value, Medical, Wages, `Rehab Cum`, `Invest Cum`)

ggplot(data, aes(x = `Location Group`, y = value, fill = variable)) +
  geom_bar(stat = "identity")