如何在R的ggplot2中绘制图表外部的文本?
要使用ggplot2在图表外部编写文本,我们可以使用annotate函数和coord_cartesian函数。annotate函数将定义文本值,而coord_cartesian函数将定义图表区域外部文本的位置。
查看下面的示例以了解其工作原理。
示例
以下代码片段创建一个示例数据框:
x<-rnorm(20) y<-rnorm(20) df<-data.frame(x,y) df
创建以下数据框:
x y 1 -0.40472483 -0.07760919 2 -0.09077911 0.40705712 3 0.04122442 -0.67552070 4 -0.78520861 -0.24918263 5 -1.38592400 0.67534026 6 -0.68027757 1.06726703 7 -0.73141825 -0.01776461 8 0.09336187 0.27947009 9 0.38625538 -0.34174606 10 -0.18627279 1.00174991 11 -1.68310315 -0.29876124 12 1.33719646 -0.13991965 13 -0.70679075 -0.11464434 14 -1.54770217 2.61299815 15 1.55050758 0.82286414 16 0.30323709 0.58833182 17 0.36705970 -2.12925379 18 0.77242047 -1.54357138 19 1.13557728 0.04046488 20 -0.09440322 -0.94294441
要加载ggplot2包并在x和y之间创建点图,请将以下代码添加到上面的代码段中:
library(ggplot2) ggplot(df,aes(x,y))+geom_point()
输出
如果您将以上所有代码片段作为一个程序执行,它将生成以下输出:
要在x和y之间创建带有图表外部文本的点图,请将以下代码添加到上面的代码段中:
ggplot(df,aes(x,y))+geom_point()+annotate("text",x=-1,y=-3.1,label="Scatterplot Display")+coord_cartesian(ylim=c(-2.5,3),clip="off")
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果您将以上所有代码片段作为一个程序执行,它将生成以下输出:
广告