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

如何在ggplot中让x轴非连续年份保持等间距排布?

解决方法

核心逻辑是将数值型的年份变量转为有序因子,ggplot对离散因子默认会按因子水平顺序等距排布,不会按数值差计算间距。
需要注意:x转为离散因子后,要显式指定group = variable参数,保证同一指标的点可以按年份顺序正常连线。

修改后的完整可运行代码如下:

# 提前加载依赖包
library(ggplot2)
library(reshape)

# 原始数据
fig1dat <- structure(list(year = c(1913L, 1928L, 1929L, 1930L, 1931L, 1932L, 1933L, 1934L, 1935L, 1936L, 1937L, 1938L), coll = c(NA, 1.67638484, 3.717201166, 23.54227405, 52.98833819, 61.88046647, NA, NA, 83.60058309, NA, NA, 93.65889213), grain = c(78.93586006, 63.19241983, 62.09912536, 65.08746356, 56.19533528, 56.19533528, 65.08746356, 68.29446064, 75.14577259, 56.04956268, 97.44897959, 74.12536443)), class = "data.frame", row.names = c(NA, -12L))

# 数据融合,同时将year转为有序因子,水平顺序和原数据年份顺序一致
fig1 <- reshape::melt(fig1dat, id.var='year')
fig1$year <- factor(fig1$year, levels = unique(fig1dat$year))

# 绘图代码
p <- ggplot(fig1, aes(x=year, y=value, col=variable, group = variable)) +
  scale_y_continuous(name = "Livestock (millions)", 
                     breaks = seq(0, 100, by=25), expand = c(0, 0), limits = c(0,100)) +
  # 改用离散x轴,默认用因子水平作为刻度
  scale_x_discrete(name = "", expand = c(0, 0.2)) +
  geom_line(size = 0.7) +
  geom_point() +
  theme_bw()

# 输出图像
print(p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:54:04