R小tip(七)ggplot加图注

这次是学习Y叔叔的博客,因为之前介绍了基础作图加图例的推送
这次介绍ggplot2的加图例的方法

我们看下annotate()这个函数

p <- ggplot() +
    annotate("point", x=1,y=1:3,shape=15, color=col) +
    annotate("text", x=1.01, y=1:3, label=names(col), hjust=0) +
    xlim(0.99, 1.2) + ylim(0, 4) + theme_void()

其中point代表图例的点,x代表一列,y代表有三行
text则是文本,即你要加的图例的文本内容


library(ggplot2)
p = ggplot(iris, aes(Sepal.Length, Sepal.Width, color=Species)) +
    geom_point() + scale_color_manual(values=col, name="")
#此时的x,y代表图例在图中的位置坐标
y = c(.77,.8,.83)
p + annotate("point", x=.2,y=y,shape=15, color=col, size=3) +
    annotate("text", x=.21, y=y, label=names(col), hjust=0)

或者用ggplotify

col = colorspace::rainbow_hcl(3)
names(col) = unique(iris$Species)

library(ggplotify)
color = col[iris$Species]

p = as.ggplot(~plot(iris$Sepal.Length, iris$Sepal.Width, col=color, pch=15))

library(ggplot2)
p2 = ggplot(iris, aes(Sepal.Length, Sepal.Width, color=Species)) +
    geom_point() + scale_color_manual(values=col, name="")
#取出p2的图例
legend = cowplot::get_legend(p2)
#加上图例
p + ggimage::geom_subview(x=.7, y=.6, subview=legend)

参考:https://mp.weixin.qq.com/s/Jqdqvs_vWj7zuDdEFzjOFA

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容