如何将带有斜体和变量的复杂标签添加到ggplot?

How to add a complex label with italics and a variable to ggplot?

我使用 expression()paste()bquote() 或某种组合阅读了很多关于此主题的 postings。我想我快要解决我的问题了,但我就是做不到。以下脚本生成标有 "y = 1 + 2(x); r^2= 0.9" 的绘图。如何将 "y" 和 "x" 设为斜体,将 "r" 设为斜体并在 "r^2" 的 2 上标?如果我之前忽略了相关内容 post,抱歉,请指导我。

df <- data.frame(x=c(1:5), y=c(1:5))
a <- 1    
b <- 2
r2 <- 0.9
eq <- paste("y = ", a, " + ", b, "(x); r^2=", r2)
ggplot(data=df, aes(x=x, y=y))+
  geom_point(color="black")+
  geom_text(x=2, y=4,label=eq, parse=FALSE)

您可以使用 substituteplotmath (https://www.rdocumentation.org/packages/grDevices/versions/3.5.1/topics/plotmath) 的组合来使文本变为斜体-

# setup
set.seed(123)
library(ggplot2)

# dataframe
df <- data.frame(x = c(1:5), y = c(1:5))

# label
eq <- substitute(
  expr =
    paste(
      italic("y"),
      " = ",
      a,
      " + ",
      b,
      "(",
      italic("x"),
      "); ",
      italic("r") ^ 2,
      " = ",
      r2
    ),
  env = base::list(a = 1,
                   b = 2,
                   r2 = 0.9)
)

# plot
ggplot(data = df, aes(x = x, y = y)) +
  geom_point(color = "black") +
  labs(subtitle = eq)

reprex package (v0.2.1)

创建于 2018-12-04

您可以使用 annotate(),它允许您直接粘贴到图中。

library(ggplot2)
ggplot(data=df, aes(x=x, y=y)) +
  geom_point(color="black") +
  annotate('text', 2.5, 4, 
           label=paste("italic(y)==", a, "+", b, 
                       "~italic(x)~';'~italic(r)^2==", r2), 
           parse=TRUE, 
           hjust=1, size=5)

产量:

数据:

df <- data.frame(x=c(1:5), y=c(1:5))
a <- 1
b <- 2
r2 <- 0.9

除了 Indrajit Patil & jay-sf, I would like to add that there is an automated way to fit regression lines (I believe there are many), using a package called ggpmisc 的回答。您想要的斜体字母已经按照这种方式进行了格式化。需要使用的代码是:

> install.packages('ggpmisc'); library(ggpmisc); formula <- y ~ x
> df <- data.frame(x=c(1:5), y=c(1:5))
> ggplot(data = df, aes(x, y)) + geom_point(color="black") + 
       geom_smooth(method =   "lm", formula = formula) + 
       stat_poly_eq(aes(label =   paste(..eq.label.., ..adj.rr.label.., sep = "~~~~")),
       formula = formula, parse = TRUE)

它还显示了拟合线,我希望这不会妨碍主要目标。

EDIT: The line can be removed using linetype = 0, compatible with most of the aesthetics in ggplot2.

... + geom_smooth(method =   "lm", formula = formula, linetype = 0) + ...