前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ggplot2 3.5新功能-高度自定义图例

ggplot2 3.5新功能-高度自定义图例

作者头像
R语言数据分析指南
发布2024-03-11 13:54:11
720
发布2024-03-11 13:54:11
举报

欢迎关注R语言数据分析指南

❝2月底ggplot2更新了最新版3.5,本节来介绍一下ggplot2 3.5版更新的内容之「图例操作部分」,使用最新版后定义图例位置将变得异常的简单,更多详细内容请参考作者官方文档。 ❞

代码语言:javascript
复制
install.packages("ggplot2") # 需要安装ggplot2 3.5
library(ggplot2)

官方文档

代码语言:javascript
复制
https://www.tidyverse.org/blog/2024/02/ggplot2-3-5-0-legends/

案例1 按属性定义图例位置

代码语言:javascript
复制
ggplot(mpg, aes(displ, hwy, shape = drv, colour = cty, size = year)) +
  geom_point(aes(alpha = cyl)) +
  guides(
    colour = guide_colourbar(position = "bottom"),
    size   = guide_legend(position = "top"),
    alpha  = guide_legend(position = "inside")) +
  theme(legend.position = "left")

案例2 自动设置刻度图长度

代码语言:javascript
复制
ggplot(mpg, aes(displ, hwy,colour = cty, shape = drv)) +
  geom_point() +
  guides(
    colour = guide_colourbar(position = "right"),
    shape   = guide_legend(position = "top"))+
  theme(legend.key.height = unit(1, "null"),
        legend.justification.top = "right")

案例3 添加外部图

代码语言:javascript
复制
x <- c(0.5, 1, 1.5, 1.2, 1.5, 1, 0.5, 0.8, 1, 1.15, 2, 1.15, 1, 0.85, 0, 0.85)
y <- c(1.5, 1.2, 1.5, 1, 0.5, 0.8, 0.5, 1, 2, 1.15, 1, 0.85, 0, 0.85, 1, 1.15)

compass_rose <- grid::polygonGrob(
  x = unit(x, "cm"), y = unit(y, "cm"), id.lengths = c(8, 8),
  gp = grid::gpar(fill = c("grey50", "grey25"), col = NA)
)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
ggplot(nc) +
  geom_sf(aes(fill = AREA)) +
  guides(custom = guide_custom(compass_rose, title = "compass"))
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 R语言数据分析指南 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 欢迎关注R语言数据分析指南
  • 官方文档
  • 案例1 按属性定义图例位置
  • 案例2 自动设置刻度图长度
  • 案例3 添加外部图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档