簡體   English   中英

為多個變量制作堆疊條 plot - R 中的 ggplot2

[英]Making a stacked bar plot for multiple variables - ggplot2 in R

我在 ggplot2 中制作堆疊條形圖時遇到了一些問題。 我知道如何使用 barplot() 制作一個,但我想使用 ggplot2 因為很容易使條形具有相同的高度(如果我沒記錯的話,使用 'position = 'fill'')。

我的問題是我有多個變量,我想將 plot 放在一起; 我的數據如下所示:

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

我想要的是一個 plot,在 X 軸上具有類別 A、B 和 C,並且對於其中的每一個,V1、V2、V3 和 V4 的值在 Y 軸上彼此堆疊。 我見過的大多數圖表 plot 在 Y 軸上只有一個變量,但我確信可以以某種方式做到這一點。

我怎么能用 ggplot2 做到這一點? 謝謝!

首先,一些數據操作。 將類別添加為變量並將數據融合為長格式。

dfr$category <- row.names(dfr)
mdfr <- melt(dfr, id.vars = "category")

現在 plot,使用名為variable的變量來確定每個條的填充顏色。

library(scales)
(p <- ggplot(mdfr, aes(category, value, fill = variable)) +
    geom_bar(position = "fill", stat = "identity") +
    scale_y_continuous(labels = percent)
)

(編輯:根據 ggplot2 v0.9 的要求更新代碼以使用scales包。)

在此處輸入圖像描述

請原諒我提出一個新的答案,而我真的只想對@Richie 提供的漂亮解決方案添加評論。 我沒有發表評論的最低要求,所以這是我的情況:

... + geom_bar(position="fill")為我的繪圖引發了錯誤,我使用的是 ggplot2 版本 0.9.3.1。 和 reshape2 而不是為熔化而 reshape 。

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

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM