[英]Plotting Year and Month in scatter plot R
I have a dataset with Year and Month number that I am trying to plot against another variable, in this case "MEI".我有一个带有年份和月份编号的数据集,我正在尝试针对另一个变量 plot,在本例中为“MEI”。 Here is a small sample of the data:
这是数据的一个小样本:
Year, Month, MEI,
1983, 5, 2.556,
1983, 6, 2.167,
1983, 7, 1.741,
1983, 8, 1.13,
1983, 9, 0.428,
1983, 10, 0.002,
1983, 11, -0.176,
1983, 12, -0.176,
1984, 1, -0.339,
1984, 2, -0.565,
Is there a way to make the x axis continuous over the years (Months-11,12,1,2).有没有办法使 x 轴多年来连续(月 11、12、1、2)。 I tried:
我试过了:
plot(weather$Month, weather$MEI, main = 'Regression for MEI Each Month Over 16.5 Years',
xlab = 'Month (From May 1983 to December 2008', ylab = 'MEI')
One solution is to generate dates from the year/month values by adding "01" as the day.一种解决方案是通过添加“01”作为日期从年/月值生成日期。 You can do that using
dplyr::mutate
.您可以使用
dplyr::mutate
来做到这一点。 If you use ggplot2
for plotting, it will make formatting a date x-axis easier too.如果您使用
ggplot2
进行绘图,它也会使格式化日期 x 轴更容易。
library(dplyr)
library(ggplot2)
weather %>%
mutate(Date = as.Date(paste(Year, Month, "01", sep = "-"))) %>%
ggplot(aes(Date, MEI)) +
geom_point() +
scale_x_date(date_labels = "%b %Y")
You could convert the months and the year to a date and then plot the date against MEI
:您可以将月份和年份转换为日期,然后将 plot 日期转换为
MEI
:
weather$date <- as.Date(paste0(weather$Year, "-", weather$Month, "-01"))
plot(weather$date, weather$MEI, main = 'Regression for MEI Each Month Over 16.5 Years',
xlab = 'Month (From May 1983 to December 2008', ylab = 'MEI')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.