【发布时间】:2015-09-29 00:50:10
【问题描述】:
我正在尝试使用下面的代码生成一个简单的散点图,其相关系数将在图上放置斜体 r。
data(mtcars)
# Load required libraries
require(ggplot2) # To derive the graphs
require(ggthemes) # To apply ggplot themes to the chart
require(scales) # For pretty breaks
# Function to generate correlation coefficient for the charts
corr_eqn <- function(x,y, digits = 2) {
corr_coef <- round(cor(x, y), digits = digits)
corr_coef <- expression(paste(italic(r)," = ", corr_coef))
return(corr_coef)
}
# Provide a scatter plot for income and health deprivation
ggplot(mtcars, aes(x = drat, y = wt)) +
geom_point(shape = 19, size = 2, aes(colour = as.factor(cyl))) +
geom_smooth(colour = "red", fill = "lightgreen", method = 'lm') +
ggtitle("Example") +
xlab("drat") +
ylab("wt") +
scale_colour_tableau("tableau10") +
geom_text(x = 3, y = 3,
label = corr_eqn(mtcars$drat,
mtcars$wt), parse = TRUE) +
theme(legend.key = element_blank(),
legend.background = element_rect(colour = 'black'),
legend.position = "bottom",
legend.title = element_blank(),
plot.title = element_text(lineheight = .8, face = "bold", vjust = 1),
axis.text.x = element_text(size = 11, vjust = 0.5,
hjust = 1, colour = 'black'),
axis.text.y = element_text(size = 11, colour = 'black'),
axis.title = element_text(size = 10, face = 'bold'),
axis.line = element_line(colour = "black"),
plot.background = element_rect(colour = 'black', size = 1),
panel.background = element_blank())
代码在控制台中以? 标记停止。运行代码:
# geom_text(x = 3, y = 3,
# label = corr_eqn(mtcars$drat, mtcars$wt), parse = TRUE) +
注释,生成如下图表:
我猜我生成格式为 r = 0.7 的方程的函数不起作用,我该如何解决?
【问题讨论】:
-
@MYaseen208 事实上,我试图使用链接问题中的讨论来编写我的函数,但它不起作用。很明显,我做错了什么。
标签: r ggplot2 annotations expression scatter-plot