【问题标题】:Converting Numbers to Month/Year in R/ggplot2在 R/ggplot2 中将数字转换为月/年
【发布时间】:2017-10-28 19:58:25
【问题描述】:

我目前正在使用包含每个观察值的“MarketStart”值的数据集。该参数的值从 -24(对应于 2012 年 1 月)到 47(对应于 2017 年 10 月)。数据收集于 2014 年 1 月开始,因此对应于 0。

我正在使用 ggplot2 显示结果,但我无法以可接受的方式标记 x 轴,这是我现在正在使用的代码:

df <- data.frame(Name,Price,ObsMonth,Producer)
plot.all <- 
  ggplot(data=df, aes(ObsMonth, Price, group = Name)) +
  geom_point(alpha=0.05) + 
  geom_line() +
  scale_x_continuous(expand = c(0, 0), limits = c(1, 36)) +
  scale_y_continuous(expand = c(0, 0), limits = c(0, 1200)) +             
  labs(x="ObsMonth", y="Price in Euro", title="title")

我暂时限制了 x 轴,但我需要在未来将数字显示为日期“2012 年 1 月,2012 年 2 月,...,2017 年 2 月”,对应于上述数值。

edit1:这里的要求是 dput(df) 提供的输出的一部分:

42L, 44L, 9L, 12L, 35L, 21L, 11L, 21L, 25L, 24L, 34L, 32L, 29L, 
41L, 36L, 33L, 30L, 43L, 44L, 31L, 39L, 35L, 27L, 42L, 23L, 28L, 
26L, 38L, 22L, 33L, 30L, 39L, 25L, 32L, 28L, 36L, 23L, 27L, 24L, 
34L, 29L, 26L, 22L, 21L, 45L, 35L, 37L, 31L, 43L, 44L, 38L, 39L, 
28L, 29L, 25L, 22L, 21L, 34L, 23L, 36L, 35L, 31L, 33L, 37L, 44L, 
26L, 30L, 27L, 24L, 27L, 25L, 29L, 28L, 26L, 30L, 31L, 31L, 30L, 
18L, 15L, 23L, 24L, 20L, 19L, 16L, 22L, 21L, 25L, 14L, 6L, 3L, 
4L, 7L, 9L, 11L, 12L, 17L, 16L, 14L, 5L, 10L, 2L, 8L, 1L, 15L, 
13L, 13L, 10L, 16L, 12L, 15L, 14L, 24L, 26L, 11L, 8L, 16L, 3L, 
6L, 13L, 12L, 29L, 19L, 4L, 1L, 9L, 17L, 25L, 28L, 7L, 18L, 10L, 
15L, 27L, 2L, 5L, 14L, 20L, 22L, 21L, 23L, 19L, 18L, 16L, 6L, 
3L, 2L, 1L, 8L, 5L, 4L, 11L, 7L, 14L, 15L, 9L, 13L, 12L, 10L, 
..... and the end part.....
, .Names = c("Name", 
"Preis", "Erhebungsmonat", "Hersteller"), row.names = c(NA, -6732L
), class = "data.frame")

【问题讨论】:

  • lubridate 包在这里会很有帮助。你能用dput(df) 的输出更新你的问题吗?有关包装的更多信息,请参阅here
  • 感谢您的回复 tyluRp。您要求的输出很长,我将其编辑为问题并查看您建议的包!
  • 尝试更小的样本; dput(head(df))

标签: r ggplot2


【解决方案1】:

您可以将date 列添加到您的数据集中。

start <- as.Date("2012-01-01")
df$date <- seq.Date(from = start, length.out = dim(df)[1], by = "month")

然后相应地改变你的情节

plot.all <-
ggplot(data=df, aes(date, Price, group = Name)) +
geom_point(alpha=0.05) +
geom_line() +
scale_x_continuous(expand = c(0, 0), limits = c(1, 36)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 1200)) +
labs(x="date", y="Price in Euro", title="title")

【讨论】:

  • 感谢您的快速回复。我尝试使用您建议的方法,但没有得到任何有用的结果。我正在使用一个包含超过 7000 个观察值的数据集,我基本上需要“替换”提到的数值,只是为了在图中显示。如果我的数据集每月只包含 1 次观察,我只能让你的方法起作用,而事实并非如此。
  • 您可以使用replace,请参阅stackoverflow.com/questions/11811027/… 如果您的数据采用“长”格式,其中ObsMonth 列的条目重复n 次,您可以使用rep(date, times = n)。你能提供一些数据(结构)吗?
  • 感谢您的另一个快速回复。我检查了您提供的链接,我认为我可以使用该方法解决问题,即使我更愿意这样做,但我认为这仍然有效。至于你对数据的要求,我做了2个截图:每月观察次数:prnt.sc/h39r8b部分结构:prnt.sc/h39rh2“Erhebungsmonat对应问题中提到的“MarketStart”。
猜你喜欢
  • 2016-03-11
  • 2016-10-27
  • 2021-12-16
  • 2021-07-31
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多