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

RStudio绘图正常,编织为PDF后X轴日期显示异常求助

解决ggplot编织PDF时日期轴显示异常的问题

你的R代码在RStudio中绘图时X轴日期显示正常,但编织成PDF后日期格式出现异常,这是因为PDF渲染设备(如LaTeX)与RStudio默认渲染设备对日期轴的格式化逻辑存在差异,以下是几种可行的解决方法:

方法1:显式指定日期轴格式

在ggplot代码中添加scale_x_date,强制定义日期的显示格式和刻度间隔,让PDF渲染时遵循你设定的规则:

total <- read.csv('spending_timeseries_total.csv')
# convert character to date
total$date_smart <- as.Date(total$date_smart, "%m/%d/%y")
# rescale the spending to million
total$spending_in_million <- total$spending/1000000
library(ggplot2)

ggplot(data=total, aes(x=date_smart, y=spending_in_million, group=top_category, color=top_category))+
  geom_line()+
  xlab('Date')+
  ylab('Spending in million')+
  labs(color="Category")+
  ggtitle('Daily Time Series Figure of Spending by Retail Category')+
  theme(legend.position="bottom")+
  theme(plot.title=element_text(hjust=0.5))+
  guides(color=guide_legend(nrow=4))+
  theme(legend.title=element_text(size=7),legend.text=element_text(size=7))+
  # 新增:指定日期显示格式与刻度间隔
  scale_x_date(date_labels = "%Y-%m-%d", date_breaks = "1 month")

你可以根据数据的时间跨度调整参数:

  • date_labels:控制日期显示格式,比如"%b %Y"会显示「Jan 2023」这样的月份缩写+年份
  • date_breaks:控制轴刻度的间隔,比如"3 months"表示每3个月显示一个刻度

方法2:统一系统日期本地化设置

有时PDF编织环境的日期locale与RStudio不一致,导致日期解析异常,可在代码开头设置统一的locale:

# 英文环境示例,Windows系统可能需改为"English_United States.1252"
Sys.setlocale("LC_TIME", "en_US.UTF-8")

如果需要中文日期,可替换为对应系统的中文locale(如Linux/Mac用"zh_CN.UTF-8",Windows用"Chinese (Simplified)_China.936")。

方法3:单独导出图表再插入PDF

若上述方法无效,可先将图表导出为独立的PDF文件,再插入到编织文档中:

# 将ggplot对象赋值给变量p
p <- ggplot(data=total, aes(x=date_smart, y=spending_in_million, group=top_category, color=top_category))+
  geom_line()+
  xlab('Date')+
  ylab('Spending in million')+
  labs(color="Category")+
  ggtitle('Daily Time Series Figure of Spending by Retail Category')+
  theme(legend.position="bottom")+
  theme(plot.title=element_text(hjust=0.5))+
  guides(color=guide_legend(nrow=4))+
  theme(legend.title=element_text(size=7),legend.text=element_text(size=7))

# 导出为PDF
ggsave("spending_timeseries.pdf", plot = p, width = 10, height = 6)

之后在R Markdown文档中用以下代码插入图片:

![Daily Time Series Figure of Spending by Retail Category](spending_timeseries.pdf)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:18:42