【问题标题】:R colouring boxplots within the box due to variables (stacked boxplot)由于变量(堆叠箱线图),R在箱内着色箱线图
【发布时间】:2016-12-09 08:03:34
【问题描述】:

我想知道如何创建一个在框中有两种不同颜色的箱线图。 例如,我正在挖掘的变量 d 是变量 b 和 c 的总和。因此,在每个框中,颜色可以表示变量 b 和 c 创建 d 的比例。 我希望这是可以理解的。

这是我的例子:

    a<-c("A","A","B","B","B","C","C","C","B","A")
    b<-c(1,2,3,4,3,4,5,6,3,4)
    c<-c(5,6,4,5,2,1,2,1,5,8)
    d<-c(6,8,7,9,5,5,7,7,8,12)
    df<-data.frame(a,b,c,d)

    boxplot(d~a)

现在我想根据变量b和c给每个框上色,这样就表明了比例。

这是一张使用 Excel 绘制的图。 example http://www.real-statistics.com/wp-content/uploads/2012/11/box-plot-excel.png

您对如何实现这一目标有任何想法吗? 谢谢!

【问题讨论】:

  • 紫色和绿色的边界也是中位数的位置吗?
  • 在我的情况下不一定如此,所以我会有一条额外的线显示中位数
  • 这让 IMO 毫无意义。请阅读?boxplot 以及该图显示的数据。在您的示例df 中,A 的箱线图范围从 7 到 10。 bc 的作用是什么?
  • 谢谢你,你当然是对的,Jimbou!我在这里忽略了一些东西...我想表明 75% 的 d 是由于 c 而 25% 的 d 是由于 a,这在箱线图中没有意义。然后我可能坚持到箱线图d 并在每个图旁边显示一个条形以指示bd 的比例。还有其他建议可以更好地绘制此图吗?
  • @KikiRiki 你将如何计算这些比率?

标签: r colors boxplot stacked


【解决方案1】:

你可以试试:

# First the boxplot
n <- boxplot(d ~ a)
# check the x values for the boxes, here it is for A 0.6 and 1.4
axis(1, seq(0, 5, 0.1))

# proportions for the b values depended on a

# the mean values calculated using another approach you mentioned in the comment
ratio <- aggregate(df[ , -1], list(df$a), mean)
# get the percentages
ratio <- ratio$b/ratio$d

# your approach:
ratio <- c(by(df, INDICES = df$a, FUN = function(x) mean(x$b/x$d)))
ratio    
A         B         C 
0.2500000 0.4620040 0.7904762

# caculate the y values for the rectangles, no matter which mean-calculation method you used
low <- diff(n$stats[c(2, 4), ])*ratio
high <- diff(n$stats[c(2, 4),])*(1-ratio)

# the final plot
n <- boxplot(d ~ a)
rect(xleft = c(0.6) + seq_along(n$n)-1, xright = 1.4 + seq_along(n$n)-1, ybottom = n$stats[2, ], ytop = n$stats[2, ]+low, col = rgb(1, 1,0 ,0.4))
rect(xleft = c(0.6) + seq_along(n$n)-1, xright = 1.4 + seq_along(n$n)-1, ybottom = n$stats[4, ], ytop = n$stats[4, ]-high, col = rgb(0, 1, 1, 0.4))

这个想法是使用rect() 将矩形绘制到方框中。您必须分别为开始和结束提供 x 和 y 值。通过使用axis 添加更多连续的x 轴,您可以轻松地从箱线图中读取x 值。 y 值取决于bcd 的比例。因此,您可以使用aggregateby 计算一个向量(此处为b)的比率,并在rect() 中生成y 值。最后rgb() 函数计算一种颜色,添加一个透明度参数。

【讨论】:

    【解决方案2】:

    You can do a pie chart to show the share of vectors b and c in d (cf. image in link)

    下面的代码显示了如何做到这一点:

    c_share = sum(c)/sum(d)
    b_share = sum(b)/sum(d)
    mat = cbind(c_share, b_share)
    pie(mat, labels=c("Share of C", "Share of B"))
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2023-03-27
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多