简体   繁体   English

在 R/ggplot2 中将数字转换为月/年

[英]Converting Numbers to Month/Year in R/ggplot2

i am currently working with a dataset which includes the value "MarketStart" for every observation.我目前正在使用一个数据集,其中包含每个观察值的“MarketStart”值。 The values of this parameter reach from -24 (corresponds to january 2012) to 47 (corresponds to october 2017).该参数的值从-24(对应2012年1月)到47(对应2017年10月)。 The data collection was started in january 2014 which therefore corresponds to 0.数据收集于 2014 年 1 月开始,因此对应于 0。

I am using ggplot2 to display the results but i am unable to label the x-axis in an acceptable manner, this is the code i am using right now:我正在使用 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")

I limited the x-axis for now, but i'll need the numbers to be displayed as dates "Jan 2012, Feb 2012,..., Dez 2017" in the future corresponding to the numeric values explained above.我现在限制了 x 轴,但我需要将数字显示为未来的日期“2012 年 1 月、2012 年 2 月、...、2017 年 Dez”,对应于上述数值。

edit1: as requested here is part of the output provided by dput(df): 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")

You could add a date column to your data set.您可以向数据集添加date列。

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

And then change your plot accordingly然后相应地改变你的情节

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM