R中的堆积条形图
我有一个看起来像这样的数据集
I have a data set that looks like this
我想绘制一个堆叠的条形图,其中X为Session,Y为不存在,Present堆叠为另一个.如何在 R
I want to plot a stacked bar chart with X being Session and Y as Absent and Present stacked one above another. How to do this in ggplot()
in R
请查看如何在SO上提问以及如何提供数据/示例.如果我们准备好了所有信息,那么人们可以轻松地为您提供帮助.
Please have a look at how to ask questions on SO and how to provide data/examples. It makes it a lot easier for people to help you if we have all the information ready to go.
我已经使用您的一些数据制作了一个表格:
I've produced a table using some of your data:
library(tidyverse)
df <- tribble(~absent, ~present, ~total, ~session,
15,8,3,'s1',
12,11,23,'s2',
12,10,23,'s4',
14,9,23,'s5',
18,5,23,'s6',
17,6,23,'s7')
聚会
就生成图表而言,首先,您需要通过调用 gather
来组织数据,以便可以将当前/不存在的变量传递给 ggplot .
Gathering
In terms of producing the chart, first you need to organise your data by calling gather
so that you can pass the present/absent variable to the fill
method in ggplot
.
gather(df, key, value, -total, -session)
这样可以整理您的数据:
This arranges your data like so:
total session key value
<dbl> <chr> <chr> <dbl>
1 3. s1 absent 15.
2 23. s2 absent 12.
3 23. s4 absent 12.
4 23. s5 absent 14.
5 23. s6 absent 18.
6 23. s7 absent 17.
7 3. s1 present 8.
8 23. s2 present 11.
9 23. s4 present 10.
10 23. s5 present 9.
11 23. s6 present 5.
12 23. s7 present 6.
绘图
然后,您可以调用 ggplot
来创建带有以下内容的柱形图:
Plotting
Then you can call ggplot
to create a column chart with the following:
ggplot(df, aes(x = session, y = value)) +
geom_col(aes(fill = key))