将R中的堆叠条形图转为ggplot2。

问题描述 投票:1回答:2

新近使用R和ggplot2进行数据分析。我想知道如何将我的数据从R转换成ggplot2格式。数据是一组5个不同类别的值,我想做一个堆积的条形图,允许我根据值将堆积的条形图分成3个部分。例:基于任意分界点的小值、中值、大值。类似于excel中的100%堆叠条形图,其中所有数值的比例加起来为1(在y轴上)。有相当多的数据(约1500个观测值),如果这也是一个有价值的事情。

这里是数据的样本(但它有大约1000个观察值的每列)(我把一个excel屏幕截图,因为我不知道是否工作下面

dput(sample-data)

similar to this image but the proportions are specific to the arbitrary data cutoffs and there are only 3 of them

r ggplot2
2个回答
2
投票

这种问题通常是数据改版的问题。请看 将data.frame从宽格式重塑为长格式。. 以下代码使用了内置的数据集 iris,有4个数字列,将数据重新整形后的数据值切成层次的条形图。

我选择的截止点是 0.20.7 但任何其他数字在 (0, 1) 就可以了。截止矢量是 brks 和级别名称 labls.

library(tidyverse)

data(iris)

brks <- c(0, 0.2, 0.7, 1)
labls <- c('Small', 'Medium', 'Large')

iris[-5] %>%
  pivot_longer(
    cols = everything(),
    names_to = 'Category',
    values_to = 'Value'
  ) %>%
  group_by(Category) %>%
  mutate(Value = (Value - min(Value))/diff(range(Value)),
         Level = cut(Value, breaks = brks, labels = labls, 
                     include.lowest = TRUE, ordered_result = TRUE)) %>%
  ggplot(aes(Category, fill = Level)) +
  geom_bar(stat = 'count', position = position_fill()) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

enter image description here


0
投票

这里有一个不需要重新整理数据的解决方案。

在这里有一个不需要重新整理数据的解决方案。diamonds 数据集带有 ggplot2. 颜色 "栏是分类的,"价格 "栏是数字的。

library(ggplot)

ggplot(diamonds) + 
    geom_bar(aes(x = color, fill = cut(price, 3, labels = c("low", "mid", "high"))),
             position = "fill") +
    labs(fill = "price")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.