r - R中的堆积柱状图

标签 r plot ggplot2 bar-chart data-visualization

我想知道(如果可能的话)如何在 中绘制这样的图R .

Example plot

例如,30 人(x 轴),工作近 300-400 小时(y 轴),每个人在 6 项特定事件中分配的时间以颜色显示。

示例数据:

| People | Act 1 | Act 2 | Act 3 | Act 4 | Act 5 | Act 6 |
|Person 1|   18  |   20  |   32  |   75  |   64  |   18  |
|Person 1|   40  |   25  |   02  |   04  |   17  |   20  |
|Person 2|   58  |   45  |   32  |   75  |   64  |   18  |
|Person 3|   10  |   15  |   11  |   28  |   15  |   92  |
|Person 1|   11  |   11  |   02  |   05  |   04  |   08  |

我正在使用此代码:
plot(table(data$worker),col=unique(data$worker))

(此代码为每个条形提供了不同的颜色)

但我找不到根据我上面提到的标准为每个条形着色的方法。

最佳答案

您需要一个堆积柱形图,它在 y 轴上显示每种事件类型的人均工作小时数的绝对值(总计)。

首先,像这样组织你的数据集:

person hours.worked activity
1      18           1
1      20           2
...
3      11           3
3      28           4
...
1      4            5
1      8            6

然后,执行以下操作:
#reproducible example (same as OP's data)
df = structure(list(person = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L),
                    hours.worked = c(18L, 20L, 32L, 75L, 64L,18L, 40L, 25L, 2L, 4L, 17L, 20L, 58L, 45L, 32L, 75L, 64L, 18L, 10L, 15L, 11L, 28L, 15L, 92L, 11L, 11L, 2L, 5L, 4L, 8L),
                    activity = c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L)),
                   .Names = c("person", "hours.worked", "activity"), 
               class = "data.frame",
               row.names = c(NA, -30L))

df$person = factor(df$person,levels=c(1,2,3)) #control person order in x axis (left to right)
df$activity = factor(df$activity,levels=c(6,5,4,3,2,1)) #control order of stacks within column (top to base)

library(ggplot2)

ggplot(data=df, aes(x=person,y=hours.worked,fill=activity)) +
  geom_col(position="stack") +
  scale_fill_manual(breaks = c(1,2,3,4,5,6), #control order of legend keys (top to bottom)
                    values = c("#F564E3","#619CFF","#00BFC4","#00BA38","#B79F00","#F8766D")) #control fill of legend keys and columns stacks (surprisingly, this will honor the order of factor levels instead of order of 'breaks')

enter image description here

关于r - R中的堆积柱状图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15456731/

相关文章:

python - 带有 python 和 matplotlib 中线条的地理数据图/ map

r - 将 ggplot2 对象与晶格对象组合在一个图中

r - ggplot2推荐的黑白配色方案

r - 是否有将 Excel 位置字符串(例如 "F3"或 "BG5")转换为 R 行列索引的干净方法?

r - 如何识别所有包含二进制表示形式的列

R:如何通过数据值对 voronoi 镶嵌进行着色?

r - 创建根据 Z 轴着色的 3D 图

r - Shiny 的 iframe 没有显示任何网站

regex - 在 R 中的字符串中插入字符

r - 如何提供带有超链接的 ggplot2 图?