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

解决geom_rect()导致geom_bar()透明度异常的R语言ggplot绘图问题

解决方法

问题出在图层绘制顺序和柱状图填充设置:

  • ggplot按代码顺序绘制图层,你先画柱状图再画背景,导致背景覆盖在柱子上,加上背景的alpha值,让柱子看起来透明
  • 你的geom_bar只设置了边框颜色colour='black',柱子内部是默认填充色,未设置为黑色

修改后的代码如下:

coloursCategories <- data.frame(ymax=c(3, 1.5, 1, -1, -1.5),
                                ymin=c(1.5, 1, -1, -1.5, -2.5),
                                xmin=as.POSIXct(c("1963-06-01")),
                                xmax=as.POSIXct(c("2022-06-01")),
                                col=c('darkblue', 'lightblue', 'white','orange', 'red'),
                                lab=c('Extreme Wet', 'Moderately Wet', 'Normal', 
                                       'Moderately Dry', 'Extreme Drought'))


spiPlot <- dataToExport %>%
  ggplot(aes(x=date, y=value)) +
  # 先绘制背景矩形,放在底层
  geom_rect(data=coloursCategories, aes(x=NULL, y=NULL, 
                                        xmin=xmin, xmax=xmax, 
                                        ymin=ymin, ymax=ymax,
                                        fill=col), alpha=0.5) +
  # 绘制柱状图,设置fill为black让柱子完全黑色,colour保持边框黑色
  geom_bar(stat="identity", colour='black', fill='black') +
  labs(x='Year', y='Standardised Precipitation Index') +
  scale_x_datetime(
    breaks=seq(min(dataToExport$date), max(dataToExport$date), 
               by= "10 years"), date_labels="%Y") +
  geom_hline(yintercept=0) +
  scale_fill_identity() +
  theme_classic() +
  theme(text=element_text(size=12, family='Calibri'))

spiPlot

关键修改点:

  • 将geom_rect移到geom_bar之前,确保背景在柱子下方
  • 给geom_bar添加fill='black'参数,让柱子内部填充为纯黑色,不再受背景透明效果影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:25:13