简体   繁体   English

R +中的时间序列图帮助需要将月份和年份列合并

[英]Time Series Graph help in r + need to combine month and year column

I am having issues combining the month and year column into a date format 我在将月份和年份列合并为日期格式时遇到问题

n month year Score
35 01 2013 1.07
29 02 2013 3.09
31 03 2013 1.08
.....

I have made the following attempts but just get a column of NAs: 我做了以下尝试,但只获得了NA的专栏:

df$date <- as.Date(with(df, paste(df$year, df$month,sep="-")), "%Y-%m")

df$Date <- with(df, sprintf("%Y-%m", year, month))

df$Date <- as.yearmon(paste(df$year, df$month), "%Y %m")

I am also struggling with creating a time series bar chart with "Score" data as the bars and "n" data plotting the line graph on the same axis 我也在努力创建一个以“得分”数据作为条形图和“ n”数据在同一轴上绘制折线图的时间序列条形图

NB NB

lapply(df, class)

shows an output of 显示的输出

$n
[1] "integer"

$month
[1] "character"

$year
[1] "character"

$Score
[1] "numeric"

For as.Date to make a valid date you need to supply a day as well. 为了使as.Date成为有效日期,您还需要提供一天。

Test data 测试数据

df = read.table(text = "n month year Score
35 01 2013 1.07
29 02 2013 3.09
31 03 2013 1.08", header = TRUE, sep = " ")
df$month = paste0("0", df$month)

Conversion 转换次数

df$date <- as.Date(paste(df$year, df$month, "01", sep="-"), "%Y-%m-%d")
>df$date
[1] "2013-01-01" "2013-02-01" "2013-03-01"

Plot 情节

Your score and n values are too different to plot at the same scale on the same chart: 您的得分和n值相差太大,无法在同一张图表上以相同比例绘制:

library(ggplot2)
ggplot(data = df, aes(x = date, y = Score)) + 
  geom_col(fill = "gray60") + 
  geom_line(aes(y = n))

在此处输入图片说明

You could normalise the scale, for example by dividing the y values by the maximum for the score and n components respectively (perhaps labelling the bars and points on each chart with their actual values), or separate your plots, or take some other action which allows you to plot both when they are so dissimilar I leave this to you to decide. 您可以对比例进行归一化,例如将y值分别除以得分和n分量的最大值(也许在每个图表上用其实际值标记条形图和点),或者分开绘图,或采取其他措施当它们是如此不同时,您可以绘制它们,我让您自己决定。

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

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