前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >「R」魔性的ggplot2,多个图例时顺序会变?

「R」魔性的ggplot2,多个图例时顺序会变?

作者头像
王诗翔呀
发布2020-07-02 15:31:47
2.9K0
发布2020-07-02 15:31:47
举报
文章被收录于专栏:优雅R优雅R

今天尝试解决使用ggplot2画图时的一个问题,图例不按规矩出牌。

ggplot2的作者们在测试时发现更新版本也出这问题了,正好可以用于简单说明。

本来是一个这样的图形

新版本变成了

而我是画两个相似的图形时出现这问题,数据结构一样,然后画图后图例的顺序变了~

根据文档,默认使用了某种“秘密魔法”?!

order: positive integer less that 99 that specifies the order of this guide among multiple guides. This controls the order in which multiple guides are displayed, not the contents of the guide itself. If 0 (default), the order is determined by a secret algorithm.

解决办法是有的,我们可以使用order选项设定。下面是一个例子:

代码语言:javascript
复制
dat <- data.frame(x = LETTERS[1:3], y = 1)
p <- ggplot(dat, aes(x, y, fill = x, colour = 1:3)) +
  geom_bar(stat = "identity") +
  theme(legend.background = element_rect(colour = "black"))

# These two are the same
p +
  guides(
    color = guide_colorbar(order = 0),
    fill = guide_legend(order = 0)
  )
p + 
  guides(
    color = guide_colorbar(order = 0),
    fill = guide_legend(order = 1)
  )

如果我们要改变图例顺序,按下面的操作,将color变成1,然后fill使用默认排序:

代码语言:javascript
复制
# And we can reverse the order
p + guides(
    color = guide_colorbar(order = 1),
    fill = guide_legend(order = 0)
  )

当然,如果你理解了上面的英文文档,怎么设定怎么排都是可以的。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 优雅R 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档