ggplot格式斜体注释

Ric*_*ruz 9 r ggplot2

我可以在ggplot注释中使用标记吗?

比方说,我有这个图:

p <- function(i) 8*i
a <- function(i) 1+4*i*(i-1)

library(ggplot2)
library(reshape2)

i <- 1:(8*365/7)
d <- data.frame(i=i,p=p(i),a=sapply(i,a))
d <- melt(d, id.vars='i')
p <- ggplot(d, aes(i, value, linetype=variable)) +
    geom_hline(yintercept=700^2) +
    geom_line() +
    scale_linetype_manual(values=c(2,1)) +
    #geom_point() +
    scale_x_continuous(breaks=(0:20)*365/7, labels=0:20) +
    #scale_y_continuous(breaks=c(0,700^2), labels=c(0,expression(L^2)))
    scale_y_sqrt() +
    #scale_y_log10() +
    annotate('text', 8*365/7, 1e3, label="P(i)=8i", hjust=1, size=3) +
    annotate('text', 8*365/7, 2.5e5, label="A(i)=1+4i(i-1)", hjust=1, size=3)
print(p + theme_classic())
Run Code Online (Sandbox Code Playgroud)

产量

我知道我可以使用fontface = 3并将所有内容都放在斜体中.但我不希望数字用斜体,只有变量i.优选地,P并且A被以斜体为好.

有任何想法吗?

pbn*_*son 17

现在这个页面是google上ggplot annotate italic的热门搜索结果.为了那些只想用斜体表示整个注释的人的利益,我正在写这篇文章.使用注释fontface选项.例:

seq(0,3.14,0.01)
qplot(x, sin(x)) +   # works the same for qplot or ggplot
annotate(geom = 'text', 
         x = 1.5, 
         y = 0.5, 
         hjust = 0.5,
         label = 'Hello, World', 
         fontface = 'italic')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Bac*_*lin 13

使用parse=TRUE并提供根据的格式化的字符串?plotmath.

p <- ggplot(d, aes(i, value, linetype=variable)) +
    geom_hline(yintercept=700^2) +
    geom_line() +
    scale_linetype_manual(values=c(2,1)) +
    scale_x_continuous(breaks=(0:20)*365/7, labels=0:20) +
    scale_y_sqrt() +
    annotate('text', 8*365/7, 1e3,
             label="P(italic(i))==8~italic(i)", parse=TRUE,
             hjust=1, size=3) +
    annotate('text', 8*365/7, 2.5e5,
             label="A(italic(i))==1+4~italic(i)(italic(i)-1)", parse=TRUE, 
             hjust=1, size=3)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Joh*_*itz 5

评分最高的答案很好,但在带有换行符的更复杂的情况下,它对我不起作用,所以我只是使用了 Unicode 斜体字符。对于您的示例:

library(Unicode)

italic_i <- u_char_inspect(u_char_from_name("MATHEMATICAL ITALIC SMALL I"))["Char"]
label1 <- paste("P(", italic_i, ")=8", italic_i, sep="")
label2 <- paste("A(", italic_i, ")=1+4", italic_i, "(", italic_i, "-1)", sep="")

i <- 1:(8*365/7)
d <- data.frame(i=i,p=p(i),a=sapply(i,a))
d <- melt(d, id.vars='i')
p <- ggplot(d, aes(i, value, linetype=variable)) +
  geom_hline(yintercept=700^2) +
  geom_line() +
  scale_linetype_manual(values=c(2,1)) +
  #geom_point() +
  scale_x_continuous(breaks=(0:20)*365/7, labels=0:20) +
  #scale_y_continuous(breaks=c(0,700^2), labels=c(0,expression(L^2)))
  scale_y_sqrt() +
  #scale_y_log10() +
  annotate('text', 8*365/7, 1e3, label=label1, hjust=1, size=3) +
  annotate('text', 8*365/7, 2.5e5, label=label2, hjust=1, size=3)
print(p + theme_classic())
Run Code Online (Sandbox Code Playgroud)

斜体注释ggplot2

编辑:我刚刚注意到用 pdf() 保存 pdf 不能正确呈现 unicode,但您可以简单地使用 cairo_pdf() 代替,它工作得很好(请参阅:ggplot2 PDF 输出中的 Unicode 字符