将具有相关系数的斜体r添加到ggplot中的散点图中

Kon*_*rad 9 expression annotations r scatter-plot ggplot2

我尝试使用下面的代码生成,将有斜体的相关系数简单的散点图[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())
Run Code Online (Sandbox Code Playgroud)

代码?在控制台中以标记停止.使用以下行运行代码:

#   geom_text(x = 3, y = 3,
#             label = corr_eqn(mtcars$drat, mtcars$wt), parse = TRUE) +
Run Code Online (Sandbox Code Playgroud)

评论,生成以下图表: 散点图

我猜我生成格式为r = 0.7的方程式的函数不起作用,我该如何解决?

aos*_*ith 6

如您所料,您只需要调整您的功能.你可以substitute这个答案中看到,但你也可以在paste这里使用.

corr_eqn <- function(x,y, digits = 2) {
  corr_coef <- round(cor(x, y), digits = digits)
  paste("italic(r) == ", corr_coef)
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请注意,如果您添加as.character了原始函数返回的内容,则会对其进行解析.但是,结果将corr_coef使用字符串而不是您想要的实际相关系数.

我还应该补充说,geom_text如果不将标签和坐标放入新的data.frame中,可能会导致分辨率不佳.

labels = data.frame(x = 3, y = 3, label = corr_eqn(mtcars$drat, mtcars$wt))
Run Code Online (Sandbox Code Playgroud)

然后使用data参数并aes用于geom_text:

geom_text(data = labels, aes(x = x, y = y,
                        label = label), parse = TRUE)
Run Code Online (Sandbox Code Playgroud)

annotategeom = "text"为避免新data.frame另一种选择.