ggplot geom_rect()错误“找不到对象”

时间:2019-03-22 14:25:47

标签: r ggplot2

我正在尝试绘制geom_rect()。为什么会收到Error in FUN(X[[i]], ...) : object 'Month' not found?如果我在控制台中运行df$Month,则对象在那里:

df$Month
#> [1] 2019-01 2019-02 2019-03
#> Levels: 2019-01 2019-02 2019-03

这是我的代码块:

library(tidyverse)
df <- tibble(Month = factor(c("2019-01", "2019-02", "2019-03")), 
             Value = c(4, 9, 7))

ggplot(df, aes(Month, Value, group = 1)) + 
  geom_line() + 
  theme_minimal() + 
  geom_rect(data = 
              data.frame(xmin = min(as.integer(df$Month)) - 0.5,
                         xmax = max(as.integer(df$Month)) + 0.5,
                         ymin = min(df$Value),
                         ymax = max(df$Value)),
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            alpha = 0.2, fill = "green")

#> Error in FUN(X[[i]], ...) : object 'Month' not found

3 个答案:

答案 0 :(得分:1)

df之后,通过在geom_line()中调用gemo_rect()返回了您想要的结果。但是,将 Month 字段保留为原样,则返回错误:错误:离散值提供给连续刻度
为此,我在{em> Month 前后加上了as.integer()

ggplot() + 
  theme_minimal() + 
  geom_rect(data = 
              data.frame(xmin = min(as.integer(df$Month)) - 0.5,
                         xmax = max(as.integer(df$Month)) + 0.5,
                         ymin = min(df$Value),
                         ymax = max(df$Value)),
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            alpha = 0.2, fill = "green") + 
  geom_line(data = df, aes(as.integer(Month), Value, group = 1))

enter image description here

您可能需要清理x轴标签,但可以达到预期的效果!

答案 1 :(得分:1)

这有效:

ggplot(df, aes(Month, Value, group = 1)) + 
  geom_line() + 
  theme_minimal() + 
  geom_rect(data = 
              data.frame(xmin = min(as.integer(df$Month)) - 0.5,
                         xmax = max(as.integer(df$Month)) + 0.5,
                         ymin = min(df$Value),
                         ymax = max(df$Value)),
            aes(x = NULL,y = NULL,xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            alpha = 0.2, fill = "green")

通过取消顶部ggplot调用中继承的x / y美学来映射。可以理解的是,这可能会造成混淆,因为?geom_rect的描述有点暗示geom_rect根本不是在寻找那些美学。

答案 2 :(得分:1)

您只需执行一个额外的步骤即可在geom_rect中设置与ggplot中的数据一致的数据帧。只需将您的最大值和最小值提供给geom_rect,它就会起作用:

ggplot(df, aes(Month, Value, group = 1)) + 
  geom_line() + 
  theme_minimal() + 
  geom_rect(aes(xmin = min(as.integer(Month)) - 0.5, 
                xmax = max(as.integer(Month)) + 0.5, 
                ymin = min(Value), 
                ymax = max(Value)),
            alpha = 0.2/nrow(df), fill = "green")