更改r ggplot中的日期?

发布于 2025-02-10 01:45:06 字数 518 浏览 0 评论 0原文

我一直在使用ggplot和x轴上绘制日期在R中的图。我已经注意到R并未将它们识别为日期,因此X轴上的顺序是错误的。我尝试了许多不同的事情,例如使用as.date(),手动编辑级别和订购X轴,但是什么都没有用。这是我的代码:

library(dplyr)
library(ggplot2)
library(hrbrthemes)

calories_data = read.csv('dailyCalories_clean.csv',header = TRUE, sep=",")

ggplot(calories_data, aes(x= ActivityDay, y=Calories, group=Id, color = Id))+
  geom_line()

这是情节

我很感谢您的任何帮助,我对此有所帮助,并且有一直在研究几个小时,没有成功。谢谢你!

I have been working on a plot in R using ggplot and plotting dates on the x axis. I have noticed that R does not recognize them as dates, and so the order on the x axis is wrong. I have tried many different things such as using as.Date(), manually editing levels and ordering the x axis, but nothing has worked. Here's my code:

library(dplyr)
library(ggplot2)
library(hrbrthemes)

calories_data = read.csv('dailyCalories_clean.csv',header = TRUE, sep=",")

ggplot(calories_data, aes(x= ActivityDay, y=Calories, group=Id, color = Id))+
  geom_line()

Here's the plot

I appreciate any help, I'm new at this and have been researching for hours with no success. Thank you!

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回心转意 2025-02-17 01:45:06

解决问题的一个选项是将日期转换为适当的日期以修复订单并使用date_labels scale> scale> scale> scale_x_date的参数以格式化日期。要转换为日期,您必须在Activityday,例如“ 2022”中添加虚假的年份:

使用一些假随机数据来模仿您的真实数据:

library(ggplot2)

set.seed(123)

calories_data <- data.frame(
  ActivityDay <- rep(c("4/1", "4/10", "5/11", "5/1"), 3),
  Id = rep(1:3, each = 4),
  Calories = runif(12, 1000, 3000)
)

calories_data$ActivityDay <- as.Date(paste("2022", calories_data$ActivityDay, sep = "/"), format = "%Y/%m/%d")

ggplot(calories_data, aes(x= ActivityDay, y=Calories, group=Id, color = Id))+
  geom_line() +
  scale_x_date(date_breaks = "5 day", date_labels = "%m/%d")

One option to fix your issue would be to convert your dates to proper dates to fix the order and use the date_labels argument of scale_x_date to format your dates. To convert to dates you have to add a fake year to your ActivityDay, e.g. "2022":

Using some fake random data to mimic your real data:

library(ggplot2)

set.seed(123)

calories_data <- data.frame(
  ActivityDay <- rep(c("4/1", "4/10", "5/11", "5/1"), 3),
  Id = rep(1:3, each = 4),
  Calories = runif(12, 1000, 3000)
)

calories_data$ActivityDay <- as.Date(paste("2022", calories_data$ActivityDay, sep = "/"), format = "%Y/%m/%d")

ggplot(calories_data, aes(x= ActivityDay, y=Calories, group=Id, color = Id))+
  geom_line() +
  scale_x_date(date_breaks = "5 day", date_labels = "%m/%d")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文