如何使日期与 ggplot() 中的数据点对齐

发布于 2025-01-11 03:37:39 字数 1332 浏览 0 评论 0原文

所以我遇到了一个问题,当我在 scale_x_date(..., date_breaks = "days") 中指定时,我只能让数据点与 x 轴标签对齐,这歪曲了数据。有人可以指出为什么他们不对齐以及如何解决它吗?

tidy_sales$Week_End <- as.Date(tidy_sales$Week_End, origin = 2022-02-06)

g1 <- ggplot(tidy_sales, aes(Week_End, y = `Value($)`)) +
  geom_line(aes(color = variable)) +
  geom_point(aes(col = variable))



g1 +  scale_x_date(date_labels="%b-%d", date_breaks  = "week",
                   limits = c(min(tidy_sales$Week_End),
                              max = max(tidy_sales$Week_End))) +
      theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))



dput(tidy_sales)
structure(list(Week_End = structure(c(19043, 19036, 19029, 19050, 
19043, 19036, 19029, 19050, 19043, 19036, 19029, 19050), class = "Date"), 
    variable = c("Total_Expenses ($)", "Total_Expenses ($)", 
    "Total_Expenses ($)", "Total_Expenses ($)", "Total_Sales($)", 
    "Total_Sales($)", "Total_Sales($)", "Total_Sales($)", "Actual_Revenue ($)", 
    "Actual_Revenue ($)", "Actual_Revenue ($)", "Actual_Revenue ($)"
    ), `Value($)` = c(6020.94, 7233.68, 5153.67, 5086, 13847.58, 
    9928.14, 15053.49, 14111.2, 12588.71, 9025.58, 13684.99, 
    12828.36)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

So I have ran into a problem where I can only get my data points to align with the x-axis labels when I specify in scale_x_date(..., date_breaks = "days") which misrepresents the data. Could someone please give some indication why they aren't aligned and how to fix it?

tidy_sales$Week_End <- as.Date(tidy_sales$Week_End, origin = 2022-02-06)

g1 <- ggplot(tidy_sales, aes(Week_End, y = `Value($)`)) +
  geom_line(aes(color = variable)) +
  geom_point(aes(col = variable))



g1 +  scale_x_date(date_labels="%b-%d", date_breaks  = "week",
                   limits = c(min(tidy_sales$Week_End),
                              max = max(tidy_sales$Week_End))) +
      theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))



dput(tidy_sales)
structure(list(Week_End = structure(c(19043, 19036, 19029, 19050, 
19043, 19036, 19029, 19050, 19043, 19036, 19029, 19050), class = "Date"), 
    variable = c("Total_Expenses ($)", "Total_Expenses ($)", 
    "Total_Expenses ($)", "Total_Expenses ($)", "Total_Sales($)", 
    "Total_Sales($)", "Total_Sales($)", "Total_Sales($)", "Actual_Revenue ($)", 
    "Actual_Revenue ($)", "Actual_Revenue ($)", "Actual_Revenue ($)"
    ), `Value($)` = c(6020.94, 7233.68, 5153.67, 5086, 13847.58, 
    9928.14, 15053.49, 14111.2, 12588.71, 9025.58, 13684.99, 
    12828.36)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文