代码绘制交替着色箱线图(ggplot2,R)存在问题
我想在方框图中绘制交替的阴影/矩形,类似于本文中的第二幅图像: 下面是我使用mtcars作为示例的代码。我将carb和cyl转换为factor,以更好地匹配我的真实数据和代码代码绘制交替着色箱线图(ggplot2,R)存在问题,r,ggplot2,rectangles,R,Ggplot2,Rectangles,我想在方框图中绘制交替的阴影/矩形,类似于本文中的第二幅图像: 下面是我使用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_box
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)
这将导致以下结果,因此目前还不完全如此。多谢各位
与此类似的预期结果:
就像我在a中所说的,数据
参数和其他参数的大小必须匹配。因此,在调用geom\u rect
时,仅从mtcars
中提取奇数。无需通过子集设置mtcars$carb来设置xmin
和xmax
,直接使用奇数。
然后交换两个几何图形,使方框位于灰色矩形上方。
还要注意,我将奇数改为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))
库(ggplot2)
mtcars$carb您将xmin/xmax限制为仅奇数(长度17),但数据长度为32。只需删除[奇数]位?@RAB否,使用geom\u rect(data=mtcars[奇数,]
。然后交换geom_rect
和geom_boxplot
,将框置于灰色条上方。@RAB和Rui Barradas:谢谢你的建议。请编辑上述内容。谢谢你,Rui Barradas。这是一个改进。但是,我唯一想更改的另一件事是,每个矩形在x轴类别1交替出现,3、5等(每个宽度为一列,从-0.5到+0.5),如原始帖子中本页顶部的图片所示。谢谢。@Sylvia Rodriguez所以现在的问题是条形图是2,4,6,8,而不是奇数?请看编辑后的代码和图表。编辑得很好!这正是我所希望的。我不介意矩形是奇数还是偶数,所以这很完美!非常感谢!
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))