【发布时间】:2018-02-21 08:04:45
【问题描述】:
我在使用 Markdown 时遇到了一个奇怪的问题。
我在下面附上 Markdown 中包含的 R 代码,用于生成相关热图。
library(reshape2)
library(knitr)
library(ggplot2)
data("cars")
# Get lower triangle of the correlation matrix
get_lower_tri<-function(cormat){
cormat[upper.tri(cormat)] <- NA
return(cormat)
}
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
reorder_cormat <- function(cormat){
# Use correlation between variables as distance
dd <- as.dist((1-cormat)/2)
hc <- hclust(dd)
cormat <-cormat[hc$order, hc$order]
}
cormat <- round(cor(cars),2)
upper_tri <- get_upper_tri(cormat)
# Reorder the correlation matrix
cormat <- reorder_cormat(cormat)
upper_tri <- get_upper_tri(cormat)
# Melt the correlation matrix
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Create a ggheatmap
ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1,1), space = "Lab",
name="Pearson\nCorrelation") +
theme_minimal()+ # minimal theme
theme(axis.text.x = element_text(angle = 45, vjust = 1,
size = 12, hjust = 1))+
coord_fixed()
ggheatmap +
geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.ticks = element_blank(),
legend.justification = c(1, 0),
legend.position = c(0.6, 0.7),
legend.direction = "horizontal")+
guides(fill = guide_colorbar(barwidth = 7, barheight = 1,
title.position = "top", title.hjust = 0.5))
代码在 R 控制台中完美运行,但在使用 markdown 时会返回此错误。
Error in FUN(X[[i]], ...) : object 'Var2' not found
Calls: <Anonymous> ... by_layer -> f -> <Anonymous> -> f -> lapply -> FUN -> FUN
Execution halted
问题似乎出在 aes 函数 (ggplot) 上。由于某些原因,它无法在 melt_cormap 对象中找到“Var2”
有什么建议吗?
非常感谢
【问题讨论】:
-
我在您的示例代码中没有看到
Var2的定义。你能说明它是在代码范围内的什么地方定义的吗? -
你的 Markdown 代码中有库(reshape2)吗?
-
@GaryWeissman 我不明白你的评论。显然
Var2应该是melted_cormat的一列。 -
如果你使用
aes(x=Var2, y=Var1, fill = value),它会改变吗? -
@AlbertoStefanelli 请参阅这篇关于创建可重现示例的帖子,尤其是关于生成最小数据集的部分:stackoverflow.com/questions/5963269/…
标签: r ggplot2 r-markdown