ggplotly绘图x轴如何设置为显示实际完整日期而非仅月份
解决方法
直接在ggplot代码中新增x轴日期格式配置即可,ggplotly会自动继承该设置,实现完整日期显示,修改后的完整代码如下:
library(ggplot2) library(plotly) library(hrbrthemes) # 对应代码中用到的theme_ipsum主题 Targets2<-structure(list(Week = structure(c(17903, 17903, 17910, 17910, 17917, 17917, 17924, 17924, 17931, 17931, 17938, 17938, 17945, 17945, 17952, 17952, 17959, 17959, 17966, 17966, 17973, 17973, 17980, 17980, 17987, 17987, 17994, 17994, 18001, 18001, 18008, 18008, 18015, 18015, 18022, 18022, 18029, 18029, 18036, 18036), class = "Date"), Type = c("Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target", "Target", "Cumilative target"), Count = c(5, 5, 8, 13, 15, 28, 20, 48, 25, 73, 25, 98, 25, 123, 25, 148, 25, 173, 25, 198, 25, 223, 25, 248, 25, 273, 25, 298, 25, 323, 25, 348, 25, 373, 25, 398, 25, 423, 25, 448)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -40L)) p <- ggplot(Targets2, aes(x = Week, y = Count, fill = Type))+ geom_area(alpha = 0.6 , size = 0.5, colour = "white", stat = "identity", orientation = "x") + scale_fill_viridis(discrete = TRUE) + # 新增x轴日期格式配置 scale_x_date(date_breaks = "1 week", date_labels = "%Y-%m-%d") + labs(fill = NULL)+ theme_ipsum() + ggtitle("Figure 1: Weekly Cumulative Projected Enrollment vs Weekly Cumulative Actual Enrollment")+ theme(legend.position = "bottom", axis.text.x = element_text(angle = 45, hjust = 1)) # 本地ggplot预览时旋转x轴标签避免重叠 p # 转换为plotly,额外加layout配置适配交互场景的显示 ggplotly(p) %>% layout(xaxis = list(tickangle = 45))
参数说明
date_breaks = "1 week":适配周度数据,每隔1周显示一个刻度date_labels = "%Y-%m-%d":指定日期显示为年-月-日的完整格式,可按需调整,比如改为%Y年%m月%d日就会显示中文格式的日期- 增加的角度旋转配置是为了避免多个日期标签挤在一起重叠
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

