gpt4 book ai didi

r - 背景填充(通过 geom_rect)在 scale_y_log10 转换后被移除

转载 作者:行者123 更新时间:2023-12-04 12:08:55 26 4
gpt4 key购买 nike

我想为使用分组数据(因子 x 轴)和对数刻度 y 轴创建的绘图添加背景填充。添加对数刻度后,背景填充将被移除。

这是一个错误,还是我做错了什么?

可重现的示例数据:我将使用 mtcars 数据,但将 cyl 变量作为一个因素。这是模仿我的数据的最简单的数据集。

library(dplyr)
library(ggplot2)
mtcars_f <- mtcars %>%
mutate(cyl.f = factor(cyl))

这适用于正常的 y 轴刻度。

mtcars_f %>% 
ggplot(aes(cyl.f, mpg)) +
geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
geom_point()

enter image description here

问题:然而,当 y 轴变换时,背景矩形填充被移除:

mtcars_f %>% 
ggplot(aes(cyl.f, mpg)) +
geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
geom_point() +
scale_y_log10()

enter image description here

注意:这是一个不同于 this similarly titled question 的问题

编辑答案: @Tung 的答案有效!这也可以通过将数据作为美学传递给 geom_rect 来解决,并将 x 轴指定为“离散”

rect_df <- 
data_frame(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5)
mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
geom_rect(data = rect_df, aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax), inherit.aes = F) +
geom_point() +
scale_y_log10() +
scale_x_discrete()

最佳答案

这是使用 annotate 的解决方法,直到您找出 geom_rect 的问题所在

library(dplyr)
library(ggplot2)

mtcars_f <- mtcars %>%
mutate(cyl.f = factor(cyl))

mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
scale_y_log10() +
scale_x_discrete() +
annotate(geom = "rect",
xmin = -Inf, ymin = 17.5, xmax = Inf, ymax = 22.5,
fill = "light blue", alpha = 0.8) +
geom_point() +
theme_classic(base_size = 12)

reprex package 创建于 2018-08-24 (v0.2.0.9000).

关于r - 背景填充(通过 geom_rect)在 scale_y_log10 转换后被移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com