ggplot绘图求助:堆叠柱状图与中位数线图例混淆及样式调整
解决方案
针对你遇到的图例异常、样式调整需求,修改后的代码及关键改动说明如下:
修改后的完整代码
library(reshape2) library(ggplot2) GS_as = data.frame(Depth = c(10,30,50,70,90), clay = c(0.99,0,0,2.86,3.62), silt = c(55.48,81.48,53.26,79.5,70.71), sand = c(43.53,18.52,46.74,17.64,25.67)) long = melt(GS_as,id = "Depth") df = data.frame(Depth = c(10,30,50,70,90), value = c(34.8,24.84,48.9,12.7,19.73), variable = c("median","median","median","median","median")) ggplot(long,aes(x=Depth,y=value,fill=variable)) + geom_bar(stat="identity") + coord_flip() + scale_y_continuous(position = "right") + scale_x_continuous(breaks = seq(10,900,by = 20),trans='reverse') + scale_fill_grey(name = "") + scale_colour_manual(name = "", values = c(median = "black")) + geom_line(data=df, aes(x=Depth, y=value, colour=variable), group=1) + geom_point(data=df, aes(x=Depth, y=value, colour=variable)) + guides( fill = guide_legend(order = 1, override.aes = list(shape = NA)), colour = guide_legend(order = 2, override.aes = list(fill = NA)) )
关键改动说明
- 统一图例层级与移除标题:通过
scale_fill_grey(name = "")和scale_colour_manual(name = "")移除两个图例的标题,使所有图例项处于同一层级。 - 固定中位数样式为黑色:用
scale_colour_manual指定中位数的颜色为黑色,替代原有的按变量映射颜色逻辑。 - 修复图例多余元素:使用
guides()函数分别调整两个图例的样式:- 给填充图例(粒度组分)添加
override.aes = list(shape = NA),去掉条目上的多余点; - 给颜色图例(中位数)添加
override.aes = list(fill = NA),去掉条目上的多余填充色块; - 通过
order参数控制图例项的展示顺序,让粒度组分在前,中位数在后。
- 给填充图例(粒度组分)添加
- 确保折线正确连接:将中位数折线的
group=variable改为group=1,保证单组数据的折线正常绘制。
内容的提问来源于stack exchange,提问作者Nic
相关产品推荐
相关产品推荐

