You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将叠加点的'Average price'图例移至图例列表底部?

解决方法:将“Average price”图例移至底部

要调整ggplot图例的排列顺序,只需通过guide_legend()的order参数控制不同图例的优先级——数值越大,图例位置越靠后。以下是修改后的完整代码:

加载库

library(dplyr)
library(ggplot2)

生成点的虚拟数据框

price.avg <- diamonds %>%
  group_by(cut, color) %>%
  summarise(price = mean(price), dummy = "1")

主绘图代码(已修改图例顺序)

diamonds %>%
  ggplot() +
  geom_bar(aes(x = cut, fill = clarity)) +
  facet_wrap(~ color, scale="free_y") +
  ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price, col = "")) +
  scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price")) + 
  scale_color_manual(
    name = "", 
    label = "Average price", 
    values = "black",
    guide = guide_legend(order = 2) # 设置该图例顺序为2,排在默认顺序1的fill图例之后
  )

说明

fill对应clarity的图例默认order值为1,将color对应“Average price”的图例order设为2,就能让它排在图例列表的底部。如果需要更清晰地控制顺序,也可以显式添加guides(fill = guide_legend(order = 1)),效果一致。

内容的提问来源于stack exchange,提问作者hnguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 03:14:58