簡體   English   中英

將具有相關系數的斜體r添加到ggplot中的散點圖中

[英]Adding italicised r with correlation coefficient to a scatter plot chart in ggplot

我嘗試使用下面的代碼生成,將有放置在情節斜體為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的方程式的函數不起作用,我該如何解決?

如您所料,您只需要調整您的功能。 您可以使用此答案中所示的 substitute ,但您也可以在此處使用paste

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

在此輸入圖像描述

請注意,如果您將as.character添加到原始函數返回的內容中,則會解析。 但是,結果將使用corr_coef作為字符串而不是您想要的實際相關系數。

我還應該補充一點,如果不將標簽和坐標放入新的data.frame中, geom_text會導致分辨率不佳。

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

然后使用data參數和aes for geom_text

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

請參閱使用geom = "text" annotate作為避免新data.frame的另一個選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM