ggplot2中y值为NA时保留x轴离散值的实现方法
解决ggplot2保留y为NA的x轴离散值问题
你的核心问题是ggplot默认会过滤掉对应y值全为NA的x轴刻度,只需调整两处即可保留所有x轴离散值:
优化步骤与代码
首先建议提前提取数据框简化代码,再强制指定x轴显示所有因子水平:
# 先提取数据框,减少重复调用 df <- tChartDF()[['df']] # 将日期列转为因子,锁定原始顺序为刻度顺序 df$Rare_event_date <- factor(df[['Rare event date']], levels = unique(df[['Rare event date']])) ggplot(df, aes( x = Rare_event_date, y = days_between )) + geom_hline(yintercept = unlist(tChartDF()[['timeScaleCL']]), color = input$tChartCLColour, lwd = input$tChartCLWidth) + geom_hline(yintercept = unlist(tChartDF()[['timeScaleUL']]), linetype = 'dashed', lwd = 1, color = 'red') + geom_hline(yintercept = unlist(tChartDF()[['timeScaleLL']]), linetype = 'dashed', lwd = 1, color = 'red') + # 强制显示所有x轴因子水平,即使对应y值为NA scale_x_discrete(limits = levels(df$Rare_event_date), expand = c(0,0)) + theme_classic() + geom_line(aes(group = 1), lwd = input$tChartLineWidth, color= input$tChartLineColour) + geom_point(size = input$tChartMarkerSize, color = input$tChartMarkerColour) + labs(title = input$tChartPlotTitle, x = input$tChartPlotXLabel, y = input$tChartPlotYLabel) + theme( plot.title = element_text(size = 24, face = 'bold', family = 'Arial', hjust = 0.5), plot.margin = margin(0, 1, 0, 0, "cm"), axis.title = element_text(size = 20, face = 'bold', family = 'Arial'), axis.text = element_text(size = 16, face = 'bold', family = 'Arial'), axis.text.x = element_text(angle = as.numeric(input$tChartXOrientation), vjust = 0.5), axis.ticks.length = unit(.25, 'cm'), ) + coord_cartesian(clip = 'off')
关键说明
- 提前将x列转为因子并指定
levels,既锁定了x轴的原始顺序,也让ggplot明确知晓所有需要展示的类别。 scale_x_discrete中设置limits = levels(df$Rare_event_date)是核心,强制ggplot显示所有因子水平,不会因对应y值为NA而自动过滤。geom_line默认会在NA处断开线条,但不会影响x轴刻度的保留显示。
内容的提问来源于stack exchange,提问作者psych0groov3
相关产品推荐
相关产品推荐

