ggplot geom_rect()错误“找不到对象"; [英] ggplot geom_rect() error "object not found"

查看:87
本文介绍了ggplot geom_rect()错误“找不到对象";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制 geom_rect().为什么在FUN(X [[i]],...)中收到错误:找不到对象'Month'?如果我在控制台中运行 df $ Month ,则对象存在:

I'm trying to plot a geom_rect(). Why do I receive an Error in FUN(X[[i]], ...) : object 'Month' not found? If I run df$Month in my console the object is there:

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

推荐答案

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

You just have an extra step of setting up a dataframe in geom_rect which coincide with data in ggplot. Simply provide your max and min values to geom_rect and it works:

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")


             

这篇关于ggplot geom_rect()错误“找不到对象";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆