r +中的时间序列图帮助需要组合月份和年份列

问题描述 投票:0回答:1

我遇到了将月份和年份列合并为日期格式的问题

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

我做了以下尝试,但只获得了一列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")

我也在努力创建一个时间序列条形图,其中“得分”数据为条形,“n”数据绘制在同一轴上的折线图

注:

lapply(df, class)

显示的输出

$n
[1] "integer"

$month
[1] "character"

$year
[1] "character"

$Score
[1] "numeric"
r plot time-series
1个回答
0
投票

要让as.Date建立有效日期,您还需要提供一天。

测试数据

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)

转变

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"

情节

您的得分和n值太大,无法在同一图表上以相同比例绘制:

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

enter image description here

您可以对比例进行标准化,例如将y值除以得分和n个组件​​的最大值(可能将每个图表上的条和点标记为实际值),或者分离您的图,或采取其他一些操作允许你在它们如此不同时绘制两者,我把它留给你来决定。

© www.soinside.com 2019 - 2024. All rights reserved.