如何在ggplot中添加带有斜体和变量的复杂标签? [英] How to add a complex label with italics and a variable to ggplot?

查看:526
本文介绍了如何在ggplot中添加带有斜体和变量的复杂标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用expression()paste()bquote()或某种组合阅读了许多有关此主题的帖子.我想我已经快要解决我的问题了,但我只是无法到达目的地.以下脚本生成标有"y = 1 + 2(x); r ^ 2 = 0.9"的图.如何斜体化"y"和"x",以及斜体化"r"和上标"r ^ 2"的2?如果我忽略了相关的早期文章,对不起,请直接引导我.

I have read many postings on this topic using expression(), paste(), and bquote(), or some combination. I think I am close to solving my problem, but I just can't get there. The following script generates a plot labelled with "y = 1 + 2(x); r^2= 0.9". How can I italicize "y" and "x", and italicize the "r" and superscript the 2 of "r^2"? If I have overlooked a relevant earlier post, sorry, but please direct me to it.

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)

推荐答案

您可以使用annotate(),将其直接粘贴到绘图中.

You could use annotate() which allows you to paste directly into the plot.

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

这篇关于如何在ggplot中添加带有斜体和变量的复杂标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆