在R中,如何从x,y,z表中绘制5x3条形图?

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

我有一个x x y x z的表格(请参见下图)。我想在一个输出中创建5个高点和3个跨度的15个条形图。对于每个条形图,我希望x轴为标签“捕获”,“确定”和“成功”,y轴为频率为“捕获”,“确定”和“成功”。我希望5个柱状图高(不确定如何说得更清楚抱歉)来表示“阈值”标签,即20、40、60、80或90。我希望3列柱状图(再次)不知道该怎么说,所以请原谅我)来表示标签“ Model”,即Model_1,Model_2或Model_3。因此,例如,当我具有Model_1和Threshold为20时,第1行第1列(5x3条形图)中的条形图应为“捕获”,“确定”,“成功”的频率。

The table I have

为我的解释不力致歉。请让我知道是否需要澄清。谢谢!

r ggplot2 plot bar-chart
1个回答
1
投票

这里有一个ggplot2选项,通过facet ing使您的“ 5高3宽”变得简单:

首先,假数据:

set.seed(42)
n <- 500
Models <- table(
  Threshold = sample(c(20, 40, 60, 80, 90), size = n, replace = TRUE),
  Outcome = sample(c("Caught", "Deferred", "Successful"), size = n, replace = TRUE),
  Model = sample(c("Model_1", "Model_2", "Model_3"), size = n, replace = TRUE)
)
Models
# , , Model = Model_1
#          Outcome
# Threshold Caught Deferred Successful
#        20     14       15         14
#        40      7       10         15
#        60     16       13         12
#        80      7       11          4
#        90     16       10         10
# , , Model = Model_2
#          Outcome
# Threshold Caught Deferred Successful
#        20     14       11         15
#        40      5       12         10
#        60     11        8         13
#        80      7       15          6
#        90     12       13         11
# , , Model = Model_3
#          Outcome
# Threshold Caught Deferred Successful
#        20     14        7         10
#        40     14       13          9
#        60      6       12         13
#        80     20        4         12
#        90     10        8         11

[用table创建的东西的一件好事是as.data.frame为我们提供了[[easy可用于ggplot2的“长数据”首选项:]]head(as.data.frame(Models)) # Threshold Outcome Model Freq # 1 20 Caught Model_1 14 # 2 40 Caught Model_1 7 # 3 60 Caught Model_1 16 # 4 80 Caught Model_1 7 # 5 90 Caught Model_1 16 # 6 20 Deferred Model_1 15

情节:

library(ggplot2) ggplot(as.data.frame(Models), aes(Outcome, Freq)) + geom_bar(stat = "identity") + facet_grid(Threshold ~ Model)

ggplot2 faceted barplot


注意:如果您的数据自然是array而不是table,我们可以轻松地做到这一点:as.table(ary)array转换为table(实际上只是下面的数组):

set.seed(42) ary <- array(sample(20, size=2*3*3, replace=TRUE), dim = c(2,3,3)) dimnames(ary) <- list(Threshold=c(20,40), Outcome=c("C","D","S"), Model=1:3) ary # , , Model = 1 # Outcome # Threshold C D S # 20 19 6 13 # 40 19 17 11 # , , Model = 2 # Outcome # Threshold C D S # 20 15 14 10 # 40 3 15 15 # , , Model = 3 # Outcome # Threshold C D S # 20 19 10 20 # 40 6 19 3 as.table(ary) ### same output as `ary` head(as.data.frame(as.table(ary))) # Threshold Outcome Model Freq # 1 20 C 1 19 # 2 40 C 1 19 # 3 20 D 1 6 # 4 40 D 1 17 # 5 20 S 1 13 # 6 40 S 1 11

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