将日期显示为ggplotly图的x轴中的实际日期,而不是仅显示为月份[重复]

Posted

技术标签:

【中文标题】将日期显示为ggplotly图的x轴中的实际日期,而不是仅显示为月份[重复]【英文标题】:Display dates as actual dates in x-axis of ggplotly plot and not as months only [duplicate] 【发布时间】:2021-11-09 02:13:48 【问题描述】:

我有下面的数据框,我想将 x 轴中的值显示为实际日期而不是月份。

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) +
    labs(fill = NULL)+
    theme_ipsum() +
    ggtitle("Figure 1: Weekly Cumulative Projected Enrollment vs Weekly Cumulative Actual Enrollment")+
    theme(legend.position = "bottom")
p

# not printed
ggplotly(p)

【问题讨论】:

【参考方案1】:

问题似乎出在ggplot,并将传递给plotly。 您可以使用 scale_x_date 更改 x 轴格式。 (标签已旋转以提高可读性)

代码

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) +
  scale_x_date(date_breaks = "1 week") +
  labs(fill = NULL)+
  ggtitle("Figure 1: Weekly Cumulative Projected Enrollment vs Weekly Cumulative Actual Enrollment")+
  theme(legend.position = "bottom",,
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

p

ggplotly(p)

输出

【讨论】:

以上是关于将日期显示为ggplotly图的x轴中的实际日期,而不是仅显示为月份[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Google 图表 API 使用 X 轴中的日期?

pyplot 轴中日期时间的格式

R:ggplot 在 x 轴上显示所有日期

课程日期 x 轴上的 ggplot geom_vline

在绘图直方图 x 轴中格式化刻度

R语言ggplot2可视化:可视化所有日期不同时段任务的持续时间将持续时间绘制成一条线(起始时间到结束时间),y轴表示活动发生的日期,x轴表示以小时为单位的时间