如何在ggplot2中将部分相关系数注释设为斜体
How to italicise part of correlation coefficient annotation in ggplot2
我无法弄清楚下面 annotate()
函数中的字母 "R" 是如何在我的绘图中变成斜体的。我试过在 paste()
之前添加 expression()
,并使用 italic()
,但随后将 "round(cor..." 开始的部分粘贴为文本,而不是计算结果。
ggplot(subset(crossnat, !is.na(homicide) & !is.na(gdppercapita)),
aes(x = gdppercapita, y = homicide)) +
geom_point(alpha = 0.4) +
ggtitle("Figure 3: Relationship between GDP per capita ($) and homicide rate") +
labs(subtitle = "n = 177 (17 countries removed as either GDP per capita or homicide data unavailable",
x = "GDP per capita ($)",
y = "Number of homicides in 2013 (per 100k of population)") +
scale_y_continuous(breaks = c(0,15,30,45,60,75,90)) +
geom_smooth(method = "loess",
formula = y ~ x,
colour = "red",
size = 0.5) +
annotate(x = 50000, y = 75,
label = paste("R = ", round(cor(crossnat$gdppercapita, crossnat$homicide, use = "complete.obs"),3)),
geom = "text", size = 4)
谢谢
编辑 - 建议的可能重复项似乎对我不起作用。我认为这可能是由于相关性的计算嵌入在 annotate()
?
中
这种格式设置很棘手。使用parse=TRUE
时需要注意白色的space。要格式化文本,您需要分两步粘贴。让我们创建一个简单的可重现示例:
ggData <- data.frame(x=rnorm(100), y=rnorm(100) )
为了代码的可读性,我建议您将文本和相关值 R 存储在 ggplot
函数之外:
textPart1 <- "paste(italic(R), \" =\")" # check the ?annotate example for \" =\"
corVal <- round(cor(ggData$x, ggData$y, use = "complete.obs"), 3)
诀窍是paste
两个变量用sep="~"
代替白色space.
ggplot(ggData, aes(x = x, y = y) ) +
geom_point(alpha = 0.4) +
annotate("text", x = 2, y = 1.5,
label = paste(textPart1, corVal, sep="~"), size = 4 , parse=TRUE)
我无法弄清楚下面 annotate()
函数中的字母 "R" 是如何在我的绘图中变成斜体的。我试过在 paste()
之前添加 expression()
,并使用 italic()
,但随后将 "round(cor..." 开始的部分粘贴为文本,而不是计算结果。
ggplot(subset(crossnat, !is.na(homicide) & !is.na(gdppercapita)),
aes(x = gdppercapita, y = homicide)) +
geom_point(alpha = 0.4) +
ggtitle("Figure 3: Relationship between GDP per capita ($) and homicide rate") +
labs(subtitle = "n = 177 (17 countries removed as either GDP per capita or homicide data unavailable",
x = "GDP per capita ($)",
y = "Number of homicides in 2013 (per 100k of population)") +
scale_y_continuous(breaks = c(0,15,30,45,60,75,90)) +
geom_smooth(method = "loess",
formula = y ~ x,
colour = "red",
size = 0.5) +
annotate(x = 50000, y = 75,
label = paste("R = ", round(cor(crossnat$gdppercapita, crossnat$homicide, use = "complete.obs"),3)),
geom = "text", size = 4)
谢谢
编辑 - 建议的可能重复项似乎对我不起作用。我认为这可能是由于相关性的计算嵌入在 annotate()
?
这种格式设置很棘手。使用parse=TRUE
时需要注意白色的space。要格式化文本,您需要分两步粘贴。让我们创建一个简单的可重现示例:
ggData <- data.frame(x=rnorm(100), y=rnorm(100) )
为了代码的可读性,我建议您将文本和相关值 R 存储在 ggplot
函数之外:
textPart1 <- "paste(italic(R), \" =\")" # check the ?annotate example for \" =\"
corVal <- round(cor(ggData$x, ggData$y, use = "complete.obs"), 3)
诀窍是paste
两个变量用sep="~"
代替白色space.
ggplot(ggData, aes(x = x, y = y) ) +
geom_point(alpha = 0.4) +
annotate("text", x = 2, y = 1.5,
label = paste(textPart1, corVal, sep="~"), size = 4 , parse=TRUE)