[英]Draw alternate rectangles in boxplots with facets (R, ggplot2)
我正在使用以下代碼。
mtcars2 <- mtcars
library(ggplot2)
mtcars2$carb <- as.factor(mtcars2$carb)
mtcars2$am <- as.factor(mtcars2$am)
sort_table <- data.frame("carb" = c(1,2,3,4,6,8),
"class" = c("class A", "class B", "class A", "class C", "class B", "class A"))
odd_numbers <- seq(1,6,2)
mtcars2 <- merge(mtcars2, sort_table, by = "carb")
ggplot(mtcars2) +
geom_rect(data = mtcars2[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 = am), position = position_dodge(0.9))
現在,我想為每個類添加構面,因此我使用以下代碼。
ggplot(mtcars2) +
geom_rect(data = mtcars2[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 = am), position = position_dodge(0.9)) +
facet_grid(cols = vars(class), scales = "free_x", switch = "x", space = "free") +
theme(panel.spacing.x = unit(0, "pt"), strip.background = element_rect(
color="black", size=0.5, linetype="solid"))
不幸的是,陰影現在僅應用於第一個構面。 如何在整個圖上對每個面應用連續陰影,以便在carb = 6
后還有另一個矩形? 謝謝。
事物將根據您提供的data.frame中存在的facet變量顯示適當的facet。 提供適當的data.frame,並進行適當的映射,例如:
df_tile <- data.frame(carb = c(1, 8, 6), class = c('class A', 'class A', 'class B'))
ggplot(mtcars) +
geom_tile(aes(x = factor(carb), y = 1, height = Inf, width = 1), data = df_tile, alpha = 0.3) +
geom_boxplot(aes(x = carb, y = mpg, fill = am), position = position_dodge(0.9)) +
facet_grid(cols = vars(class), scales = "free_x", space = "free") +
theme(panel.spacing.x = unit(0, "pt"), strip.background = element_rect(
color="black", size=0.5, linetype="solid"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.