使用as.yearmon()转换年月格式后,绘图时间仅显示年份(如2017.0)的问题求助
Got it, let's fix this date formatting headache with as.yearmon()! I’ve dealt with this exact issue a bunch of times, so here are the go-to solutions based on which plotting tool you’re using:
Solution for Base R Plots
When using base R’s plot() function, it doesn’t automatically recognize the human-readable format of yearmon objects. You’ll need to manually define the axis labels using format() and axis():
library(zoo) # Sample data dates <- as.yearmon(seq(as.Date("2017-01-01"), as.Date("2019-12-01"), by = "month")) values <- rnorm(length(dates)) # First plot without the x-axis plot(dates, values, xaxt = "n", xlab = "Date") # Add the x-axis with your desired format: "%Y/%b" gives 2017/Jan, 2017/Feb, etc. axis(1, at = dates, labels = format(dates, "%Y/%b"), las = 2) # Use las=2 to rotate labels vertically and prevent overlap
Solution for ggplot2 Plots
ggplot2 also defaults to showing yearmon as decimal values (like 2017.0), but you can fix this with either the zoo package’s built-in scale or by converting to a Date type:
Option 1: Use scale_x_yearmon() (from zoo)
This is the most direct approach since it works natively with yearmon objects:
library(ggplot2) library(zoo) # Sample dataframe df <- data.frame( date = as.yearmon(seq(as.Date("2017-01-01"), as.Date("2019-12-01"), by = "month")), value = rnorm(length(date)) ) ggplot(df, aes(x = date, y = value)) + geom_line() + scale_x_yearmon(format = "%Y/%b", n = 12) # n=12 ensures all months are displayed; adjust this number if labels overlap
Option 2: Convert yearmon to Date and use scale_x_date()
If you prefer working with Date objects, convert your yearmon column first, then set the label format:
df$date_as_date <- as.Date(df$date) ggplot(df, aes(x = date_as_date, y = value)) + geom_line() + scale_x_date(date_labels = "%Y/%b", date_breaks = "1 month")
The key takeaway is that you need to explicitly tell your plotting function how to format the yearmon axis labels—they won’t do it automatically!
内容的提问来源于stack exchange,提问作者Gui_99

