代码绘制问题交替显示为阴影框(ggplot2,R)

时间:2019-07-02 04:18:24

标签: r ggplot2 rectangles

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

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

 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

有人可能有建议吗?谢谢。

编辑

在评论之后,我按如下方式编辑了代码: -已删除[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))

这将导致以下结果,因此还不完全清楚。谢谢。

enter image description here

所需的结果与此类似:

enter image description here

1 个答案:

答案 0 :(得分:1)

就像我在comment中所说的那样,data参数和其他参数的大小必须匹配。因此,在对odd_numbers的调用中仅从mtcars中提取geom_rect。并且无需通过子集xmin来设置xmaxmtcars$carb,而直接使用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))

enter image description here

相关问题