geom_vline和facet_wrap在ggplot中出错

4
我将尝试运行以下代码:

我正在尝试运行以下代码:

temp_plotdata <- data.table(Treatment_Code = c('Control', 'Control', 
                                               'Second Mailing', 'Second Mailing', 
                                               'First Mailing', 'First Mailing'),
                            Q9 = c(9, 14, 10, 3, 1, 4))

output_gg <-
  ggplot(temp_plotdata, aes(x = Q9)) +
  geom_histogram(binwidth = 1, fill = 'lightblue') +
  geom_vline(data = temp_plotdata[, summary(Q9)[c(2,3,5)], by=Treatment_Code],
             aes(xintercept = V1),
             linetype = 'dashed', color = 'darkred') +
  facet_wrap(~Treatment_Code, ncol = 1)

我收到了以下错误信息:

Error in provideDimnames(x, sep = sep, base = base) : 'dimnames' applied to non-array

我知道问题出在代码的geom_vline部分,因为当我运行没有这些行或者运行类似geom_vline(xintercept = c(3, 5, 8))的代码时,它可以正常工作。我也尝试将来自geom_vline的数据先转换为单独的数据框,但这并没有起作用。
去年我运行了非常相似的代码,它可以正常工作,所以我不确定是geom_vline发生了什么变化还是由于新数据或一些意外更改导致我的代码不正确。
感谢您能提供的任何帮助。

我正在使用2.1.0版本。我认为这是最新的版本。 - Dan P
1个回答

2
这是因为data.table返回的汇总列V1的类别是表格,而不是数值向量。将其改为向量即可解决问题。
output_gg <-
  ggplot(temp_plotdata, aes(x=Q9)) +
  geom_histogram(binwidth=1, fill='lightblue') +
  geom_vline(data=temp_plotdata[, as.vector(summary(Q9)[c(2,3,5)]), by=Treatment_Code],
             aes(xintercept=V1),
             linetype='dashed', color='darkred') +
  facet_wrap(~ Treatment_Code, ncol=1)

比较数据框在之前和之后的结构:

str(temp_plotdata[, summary(Q9)[c(2,3,5)], by=Treatment_Code])
Classes ‘data.table’ and 'data.frame':    9 obs. of  2 variables:
  $ Treatment_Code: chr  "Control" "Control" "Control" "Second Mailing" ...
  $ V1            :Class 'table'  num [1:9] 10.25 11.5 12.75 4.75 6.5 ...
- attr(*, ".internal.selfref")=<externalptr>
str(temp_plotdata[, as.vector(summary(Q9)[c(2,3,5)]), by=Treatment_Code])
Classes ‘data.table’ and 'data.frame':    9 obs. of  2 variables:
  $ Treatment_Code: chr  "Control" "Control" "Control" "Second Mailing" ...
  $ V1            : num  10.25 11.5 12.75 4.75 6.5 ...
- attr(*, ".internal.selfref")=<externalptr>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接