Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/84.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中的ggplot2_R_Ggplot2 - Fatal编程技术网

为多个变量制作堆叠条形图-R中的ggplot2

为多个变量制作堆叠条形图-R中的ggplot2,r,ggplot2,R,Ggplot2,我在ggplot2中制作堆叠条形图时遇到一些问题。我知道如何使用barplot()创建一个,但我想使用ggplot2,因为它很容易使条形具有相同的高度(如果我没有弄错的话,使用“位置=”填充“”) 我的问题是,我有多个变量,我想绘制在彼此之上;我的数据如下所示: dfr <- data.frame( V1 = c(0.1, 0.2, 0.3), V2 = c(0.2, 0.3, 0.2), V3 = c(0.3, 0.6, 0.5), V4 = c(0.5, 0.1, 0.

我在ggplot2中制作堆叠条形图时遇到一些问题。我知道如何使用barplot()创建一个,但我想使用ggplot2,因为它很容易使条形具有相同的高度(如果我没有弄错的话,使用“位置=”填充“”)

我的问题是,我有多个变量,我想绘制在彼此之上;我的数据如下所示:

dfr <- data.frame(
  V1 = c(0.1, 0.2, 0.3),
  V2 = c(0.2, 0.3, 0.2),
  V3 = c(0.3, 0.6, 0.5),
  V4 = c(0.5, 0.1, 0.7),
  row.names = LETTERS[1:3]
)

dfr首先,一些数据操作。将类别添加为变量,并将数据转换为长格式

dfr$category <- row.names(dfr)
mdfr <- melt(dfr, id.vars = "category")
(编辑:根据ggplot2 v0.9以来的要求,更新代码以使用比例软件包。)


请原谅我提出了一个新的答案,而我真的只是想对@Richie提供的漂亮解决方案添加一点评论。我没有足够的理由发表评论,所以我的情况如下:

…+geom_bar(position=“fill”)
在打印时出错,我使用的是ggplot2版本0.9.3.1。和重塑2,而不是重塑熔化

error_message:
*Mapping a variable to y and also using stat="bin".
  With stat="bin", it will attempt to set the y value to the count of cases in each group.
  This can result in unexpected behavior and will not be allowed in a future version of ggplot2.
  If you want y to represent counts of cases, use stat="bin" and don't map a variable to y.
  If you want y to represent values in the data, use stat="identity".
  See ?geom_bar for examples. (Deprecated; last used in version 0.9.2)
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
Error in pmin(y, 0) : object 'y' not found*

所以我把它改成了
geom\u bar(stat='identity')
,它可以工作。

你也可以这样做

library(tidyverse)
dfr %>% rownames_to_column("ID") %>% pivot_longer(!ID) %>%
  ggplot() +
  geom_col(aes(x = ID, y = value, fill = name), position = 'fill')


@lselzer,伟人所见略同!在我看来,下一次,你应该毫不犹豫地发布你的答案,即使答案非常相似。非常感谢里奇!这对我有用。但我有一个问题——如果我用‘p’来画它,它对我不起作用。。。我在连续缩放(c(“y”、“ymin”、“ymax”、“yend”、“yintercept”)中遇到错误:未使用的参数(formatter=“percent”)@RachitAgrawal,我认为您必须更新代码。使用库(scales),然后更改上面的代码:缩放连续(labels=percent)新建
ggplot
语法显然需要
geom\u bar(position=“fill”,stat=“identity”)
+1用于添加样本数据。欢迎使用SO。如果您发现任何答案都有帮助,请选择一个作为您接受的答案。感谢您发布此消息,我不知道如何修复此错误!
library(tidyverse)
dfr %>% rownames_to_column("ID") %>% pivot_longer(!ID) %>%
  ggplot() +
  geom_col(aes(x = ID, y = value, fill = name), position = 'fill')