简体   繁体   English

在 r 中绘制堆叠和分组的条形图

[英]Plotting a stacked and grouped barchart in r

I'm currently trying to plot some data in R, and not really succeeding.我目前正在尝试在 R 中绘制一些数据,但并没有真正成功。 My data looks like this:我的数据如下所示:

My data is stored in a data frame called "Head": My response variable is a factor (called "colour") with only two levels ("black" and "white") My first (and main) explanatory variable is a factor (called "Year" with two levels ("Year 1996" and "Year 2019"). My secondary explanatory variable is a factor (called "DateClass") with three levels ("A", "B" and "C"). So the dataset looks something like this:我的数据存储在一个名为“Head”的数据框中:我的响应变量是一个因子(称为“颜色”),只有两个级别(“黑色”和“白色”)我的第一个(也是主要的)解释变量是一个因子(称为“Year”,具有两个级别(“Year 1996”和“Year 2019”)。我的第二个解释变量是一个具有三个级别(“A”、“B”和“C”)的因子(称为“DateClass”)。所以数据集如下所示:

Colour Year DateClass颜色年份日期类

Black 1996 A黑色 1996 A

Black 2019 B黑色2019 B

White 1996 A白色 1996 A

Black 1996 C黑色 1996 C

White 2019 B白色2019 B

White 1996 B白色 1996 B

...etc ...等等

I want to plot "head colour" as a proportion of white/black vs "Year" and "DateClass".我想将“头部颜色”绘制为白/黑与“年份”和“日期类”的比例。 I had thought of a grouped barchart and stacking Black and White, but I don't know how to do it.曾经想过分组条形图和黑白堆叠,但不知道怎么做。 Any suggestions?有什么建议? Would you plot the stacks of "colour" as percent or as total counts?您会将“颜色”的堆栈绘制为百分比还是总计数?

Thank you for your answers, best regards谢谢你的回答,最好的问候

Is this what you are looking for?这是你想要的?

DATA :数据

df <- data.frame(Colour = c("Black", "Black", "White", "Black", "White", "White"),
                 Year = c(1996, 2019, 1996, 1996,2019, 1996),
                 DateClass = c("A", "B", "A", "C", "B", "B"))

EDITED SOLUTION :编辑解决方案

First, aggregate the data to obtain the proportions of Colour by DateClass in subsets of df by Year==2019 and, respectively, Year==2019 ;首先,聚合数据,以获得的比例ColourDateClass中的子集dfYear==2019和分别Year==2019 ; store the results in df1996 and df2019 :将结果存储在df1996df2019

df1996 <- aggregate(
  x = df$DateClass[df$Year==1996],
  by = list(df$Colour[df$Year==1996]),
  function(x) prop.table(table(x)))

df2019 <- aggregate(
  x = df$DateClass[df$Year==2019],
  by = list(df$Colour[df$Year==2019]),
  function(x) prop.table(table(x)))

Now plot the two dataframes side by side using a two-panel layout:现在使用两面板布局并排绘制两个数据框:

par(mfrow = c(1,2))
barplot(df1996[,-1], cex.names = 0.8, col = c("blue","red"),
        main = "Black/White by DateClass in 1996", cex.main = 0.8,
        xlab = "1996", ylab = "Proportions")

barplot(df2019[,-1], cex.names = 0.8, col = c("blue","red"),
        main = "Black/White by DateClass in 2019", cex.main = 0.8,
        xlab = "2019", ylab = "Proportions")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM