【问题标题】:Facet_grid: Error in Factor() Object not FoundFacet_grid:未找到因子()对象中的错误
【发布时间】:2021-12-26 02:33:50
【问题描述】:

我想ggplotfacet_grid 在这种我的数据类型上包含一个带有[list of vectors][1] 的列,就像这个data in this answerthis answer 一样。

set.seed(1)
df <- data.frame(xx = 1:10, x1 = rnorm(10), x2 = rnorm(10), x3 = rnorm(10), x4 = rnorm(10), x5 = rnorm(10), x6 = rnorm(10), x7 = rnorm(10), x8 = rnorm(10), x9 = rnorm(10), x10 = rnorm(10), x11 = rnorm(10), x12 = rnorm(10))
reshapp <- reshape2::melt(df, id = "xx")
new_df <- data.frame(y = reshapp$value, x = reshapp$xx, sd = rep(rep(c(sd = 1, sd = 3, sd = 5, sd = 10), each = 10), each = 3), phi = rep(rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), each = 10), 4))

new_df$sd <- factor(new_df$sd, levels = new_df$sd, labels = paste("sd ==", new_df$sd))

我在R 代码Error in factor(phi, levels = phi, labels = paste("phi ==", phi)) : object 'phi' not found. 的这个阶段收到此错误消息

我想如果我能够解决这个错误,我就可以继续前进。

new_df$phi <- with(new_df, factor(phi, levels = phi, labels = paste("phi ==", phi)))

ggplot(new_df, aes(x = reshapp$xx, y = reshapp$value)) +  geom_line() +  geom_point() + scale_y_continuous(expand = c(0.0, 0.00)) + labs(x = 'Time', y = 'Series') + facet_grid(sd ~ phi, scales = "free_y",  labeller = label_parsed) +  theme_bw()

如何摆脱这个错误:Error in factor(phi, levels = phi, labels = paste("phi ==", phi)) : object 'phi' not found

我希望输出类似于,只是0.8 将是(0.4, 0.4)0.9 将是(0.45, 0.45)0,95 将是(0.35, 0.6).

【问题讨论】:

  • 如果您需要更多说明以便更好地理解我的问题,请在评论中提问。

标签: r ggplot2 facet-grid


【解决方案1】:

如果您对完整的 tidyverse 工作流程持开放态度,您可以使用:

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(-xx) %>% 
  mutate(id = as.numeric(gsub("x", "", name))) %>% 
  arrange(id, xx) %>% 
  select(-id) %>% 
  mutate(sd = rep(rep(c(sd = 1, sd = 3, sd = 5, sd = 10), each = 10), each = 3),
         phi = rep(rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), each = 10), 4)) %>% 
  mutate(sd = factor(sd, levels = sd, labels = paste("sd =", sd)),
         phi = factor(phi, levels = phi, labels = gsub("c", "", paste("\U03D5 =", phi)))) %>%   
  ggplot(aes(x = xx, y = value)) +
  geom_line() + 
  geom_point() +
  scale_y_continuous(expand = c(0.0, 0.00)) +
  labs(x = "Time", y = "Series") +
  facet_grid(sd ~ phi, scales = "free_y") + 
  theme_bw()

这会产生

【讨论】:

  • 你的解决方案很神奇。
  • 真的没有。我对ggplot 函数之前的部分非常满意,但它确实有效。也许它会给你一些关于这个和未来问题的见解。
  • 如何删除图中的c
  • @DanielJames 发布了更新。
  • 请回答edit如何增加右侧标签sd = c(sd = 1, sd = 3, sd = 5, sd = 10)和顶部labels标签phi = c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6))。还有,如何让它们变得粗体。
猜你喜欢
  • 2013-02-20
  • 2017-08-26
  • 2013-11-25
  • 1970-01-01
  • 2015-12-28
  • 2013-06-22
  • 1970-01-01
  • 2018-12-18
  • 2017-12-27
相关资源
最近更新 更多