【问题标题】:Problem with code drawing alternately shaded boxplot (ggplot2, R)代码绘制交替阴影箱线图的问题(ggplot2,R)
【发布时间】:2019-11-12 16:13:54
【问题描述】:

我想在箱线图中绘制交替的阴影/矩形,类似于本文中的第二张图片: Adding shading alternate areas for categorical variable in a bar plot in ggplot2

以下是我的代码,以 mtcars 为例。我将 carb 和 cyl 转换为 factor 以更好地匹配我的真实数据和代码

 library(ggplot2)
 odd_numbers <- seq(1,33,2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$cyl <- as.factor(mtcars$cyl)
 ggplot(mtcars) + 
   geom_boxplot(aes(x = carb, y = mpg, fill = cyl), position = position_dodge(0.9)) + 
   geom_rect(data = mtcars, aes(x = carb, y = mpg), 
             xmin= as.numeric(mtcars$carb[odd_numbers]) - 0.5, 
             xmax = as.numeric(mtcars$carb[odd_numbers]) + 0.5, 
             ymin = -Inf, 
             ymax = Inf, fill='grey', alpha=0.5)

我以为x轴为数值的问题在代码中已经解决了,但还是有问题:

警告:忽略未知的美学:x,y

错误:美学长度必须为1或与数据相同(32):xmin,xmax

请问有人给点建议吗?谢谢。

编辑

在 cmets 之后,我编辑了代码,如下所示: - 删除了[odd_numbers] - 交换geom_boxplotgeom_rect的顺序

代码:

 library(ggplot2)
 odd_numbers <- seq(1,33,2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$cyl <- as.factor(mtcars$cyl)
 ggplot(mtcars) + 
   geom_rect(data = mtcars, aes(x = carb, y = mpg), 
         xmin= as.numeric(mtcars$carb) - 0.5, 
         xmax = as.numeric(mtcars$carb) + 0.5, 
         ymin = -Inf, 
         ymax = Inf, fill='grey', alpha=0.5) + 
   geom_boxplot(aes(x = carb, y = mpg, fill = cyl), position = position_dodge(0.9))

这会导致以下结果,所以还没有。谢谢。

想要的结果与此类似:

【问题讨论】:

  • 您将 xmin/xmax 限制为仅奇数(长度 17),但您的数据长度为 32。只需删除 [odd_numbers] 位?
  • @RAB 不,使用geom_rect(data = mtcars[odd_numbers, ]。并交换 geom_rectgeom_boxplot 以使框覆盖灰色条。
  • @RAB 和 Rui Barradas:感谢您的建议。请在上面进行编辑。

标签: r ggplot2 rectangles


【解决方案1】:

就像我在comment 中所说,data 参数和其他参数的大小必须匹配。因此,在对geom_rect 的调用中,仅从mtcars 中提取odd_numbers。并且不需要通过子集mtcars$carb来设置xminxmax,直接使用odd_numbers
并交换两个几何图形以使框覆盖灰色矩形。
另请注意,我已将 odd_numbers 更改为 32,而不是 33。nrow(mtcars) 之后的一个值会引发错误。

library(ggplot2)

mtcars$carb <- as.factor(mtcars$carb)
mtcars$cyl <- as.factor(mtcars$cyl)

odd_numbers <- seq(1, 32, 2)

ggplot(mtcars) + 
   geom_rect(data = mtcars[odd_numbers, ], 
             xmin = odd_numbers - 0.5, 
             xmax = odd_numbers + 0.5, 
             ymin = -Inf,
             ymax = Inf, fill = 'grey', alpha = 0.5) +
   geom_boxplot(aes(x = carb, y = mpg, fill = cyl), 
                position = position_dodge(0.9))

【讨论】:

  • 谢谢你,瑞巴拉达斯。这是一个进步。但是,我想更改的唯一另一件事是每个矩形在 x 轴类别 1、3、5 等处交替出现(每个矩形的宽度为一列,从 -0.5 到 +0.5),根据图像在原始帖子中一直引用此页面顶部。谢谢。
  • @SylviaRodriguez 所以现在的问题是柱子在 2、4、6、8,而不是奇数?查看编辑后的代码和图表。
  • 伟大的编辑!这正是我所希望的。我不介意矩形是偶数还是奇数,所以这是完美的!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
相关资源
最近更新 更多