gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:58:52 32 4
gpt4 key购买 nike

我正在尝试使用下面的代码生成一个简单的散点图,其相关系数将在图上放置斜体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) +

评论后,生成如下图表: scatter plot

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

最佳答案

正如您所怀疑的,您只需要调整您的功能即可。您可以使用substitute,如 this answer 中所示。 ,但您也可以在此处使用paste

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

enter image description here

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

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

labels = data.frame(x = 3, y = 3, label = corr_eqn(mtcars$drat, mtcars$wt))

然后使用 data 参数和 aes 来表示 geom_text:

geom_text(data = labels, aes(x = x, y = y,
label = label), parse = TRUE)

请参阅使用 geom = "text" 进行注释,作为避免使用新 data.frame 的另一个选项。

关于r - 将带有相关系数的斜体 r 添加到 ggplot 中的散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337922/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com