從以下dataframedf:
df <- data.frame(Date=as.POSIXct(c("2002-07-01","2002-06-01","2002-05-01","2002-04-01","2002-03-01")),
Cat1=c(1,0,1,0,0),
Cat2=c(1,1,1,0,0),
Cat3=c(0,1,1,0,1),
Cat4=c(0,0,1,1,0))
df <- tidyr::pivot_longer(df, -1)
使用scale_x_datetime這個 requirePOSIXct類物件時,否則會報錯。
錯誤:無效輸入:time_trans 僅適用于 POSIXct 類的物件
ggplot(df,
aes(x = Date, y = factor(name, levels = rev(unique(name))),
fill = as.factor(value)))
geom_tile(color = "black")
scale_fill_manual(values = c("white", "grey50"))
theme_void()
theme(legend.position = "none",
axis.text = element_text(size = 8),
plot.margin = margin(20, 20, 20, 20),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size =5))
scale_x_datetime(date_breaks = "1 month",
labels = scales::date_format("%m-%Y"))
使用以下輸入:

通過檢查Date列的范圍,這與 x 軸的繪圖示簽不匹配。
range(df$Date)
有沒有人如何解決這個問題?
uj5u.com熱心網友回復:
使用date類,和scale_x_date
library(ggplot2)
# changing the class by constructing your data differently
df <- data.frame(Date=as.Date(c("2002-07-01","2002-06-01","2002-05-01","2002-04-01","2002-03-01")),
Cat1=c(1,0,1,0,0),
Cat2=c(1,1,1,0,0),
Cat3=c(0,1,1,0,1),
Cat4=c(0,0,1,1,0))
df <- tidyr::pivot_longer(df, -1)
ggplot(df,
aes(x = Date, y = factor(name, levels = rev(unique(name))),
fill = as.factor(value)))
geom_tile(color = "black")
scale_fill_manual(values = c("white", "grey50"))
theme_void()
theme(legend.position = "none",
axis.text = element_text(size = 8),
plot.margin = margin(20, 20, 20, 20),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size =5))
scale_x_date(labels = scales::date_format("%m-%Y"))

由reprex 包(v2.0.1)于 2021 年 11 月 2 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345867.html
