堆积条形图,百分比在单独的列中

Stacked bar plot with percentages in separate columns

我正在尝试使用 ggplot2 或 r 中的 barplot 函数使用以下数据绘制堆积条形图。我都失败了。

str(ISCE_LENGUAJE5_APE_DEC)
'data.frame':   50 obs. of  5 variables:
$ Nombre             : Factor w/ 49 levels "C.E. DE BORAUDO",..: 6 5 25 21 16 7 27 45 24 38 ...
$ v2014_5L_porNivInsu: int  100 93 73 67 67 65 63 60 59 54 ...
$ v2014_5L_porNivMini: int  0 7 22 26 32 32 37 26 34 35 ...
$ v2014_5L_porNivSati: int  0 0 4 6 2 3 0 12 6 10 ...
$ v2014_5L_porNivAvan: int  0 0 1 2 0 0 0 2 1 2 ...

整数是百分比值:每个观察值的 v2014... 列的总和为 100。

我曾尝试使用 ggplot2,但我只能绘制其中一个变量,而不是所有四个变量的堆叠条。

ggplot(ISCE_LENGUAJE5_APE_DEC, aes(x=Nombre, y= v2014_5L_porNivInsu)) + geom_bar(stat="identity")

我不知道如何将所有四列的值传递给 y 参数。

如果我只传递 x,我会得到一个错误:

ggplot(ISCE_LENGUAJE5_APE_DEC, aes(x=Nombre)) + geom_bar(stat="identity")
Error in exists(name, envir = env, mode = mode) : 
argument "env" is missing, with no default

我找到了 this answer,但不了解所使用的数据转换。感谢您提供的任何帮助。

ggplot2 处理以 "long" 格式表示的数据。包 reshape2 中的函数 melt 是你的朋友。

因为你没有提供可重现的例子,我生成了一些数据。

v2014 <- data.frame(v2014_5L_porNivInsu = sample(1:100, 50, replace = TRUE),
                    v2014_5L_porNivMini = sample(1:50, 50, replace = TRUE),
                    v2014_5L_porNivSati = sample(0:10, 50, replace = TRUE),
                    v2014_5L_porNivAvan = sample(0:2, 50, replace = TRUE))

v2014_prop <- t(apply(dummy[, -1], 1, function(x) {x / sum(x) * 100}))

ISCE_LENGUAJE5_APE_DEC <- data.frame(Nombre = factor(sample(1:100, 50)),
                                     v2014_prop)

您首先使用 melt 以长格式表达您的 table。

library(reshape2)
gg <- melt(ISCE_LENGUAJE5_APE_DEC, id = "Nombre")

看看你的新 table、gg 长什么样。

str(gg)
head(gg)

在你的 ggplot 中,你使用 data.frame gg。 x-axis 是 Nombre,y-axis 是值,即比例,由变量列定义的不同填充颜色分割,您可以在其中找到 v2014_... 表示为因子水平而不是列 headers感谢融化功能。

library(ggplot2)
ggplot(gg, aes(x = Nombre, y = value, fill = variable)) + 
  geom_bar(stat = "identity")