繁体   English   中英

我如何在 R 中按季度给出 plot 和 dataframe ?

[英]How can I plot a dataframe in R given in quarterly years?

我有一个数据集:

   Country Time      Value
1   USA    1999-Q1   292929
2   USA    1999-Q2   392023
3.  USA    1999-Q3   9392992
4

.... 等等。 现在我想 plot 这个 dataframe 时间在 x 轴上,y 是值。 但我面临的问题是我不知道如何 plot 时间。 因为它没有在月/日/年中给出。 如果是这种情况,我只需编码as.Date( format = "%m%d%y") 我不允许更改季度名称。 所以当我 plot 它时,它应该保持这种状态。 我怎样才能做到这一点?

先感谢您!

假设最后的注释中显示 DF,将 Time 列转换为yearqtr class 直接表示年份和季度(而不是使用Date类)并使用scale_x_yearqtr 有关更多信息,请参阅?scale_x_yearqtr

library(ggplot2)
library(zoo)

fmt <- "%Y-Q%q"
DF$Time <- as.yearqtr(DF$Time, format = fmt)
ggplot(DF, aes(Time, Value, col = Country)) + 
  geom_point() + 
  geom_line() +
  scale_x_yearqtr(format = fmt)

(图后续) 截屏

也可以将其转换为每个国家一列的宽格式动物园 object,然后使用autoplot 使用下面注释中的DF

fmt <- "%Y-Q%q"
z <- read.zoo(DF, split = "Country", index = "Time", 
  FUN = as.yearqtr, format = fmt)
autoplot(z) + scale_x_yearqtr(format = fmt)

笔记

Lines <- "
Country Time Value 
1 USA 1999-Q1 292929 
2 USA 1999-Q2 392023 
3 USA 1999-Q3 9392992"
DF <- read.table(text = Lines)

使用 ggplot2:

library(ggplot2)

ggplot(df, aes(Time, Value, fill = Country)) + geom_col()

在此处输入图像描述

我知道其他人已经回答了,但我认为这个更一般的答案也应该在这里。

当你做as.Date()时,你只能做开始。 我在您的数据框上尝试了它(我称之为df ),它起作用了:

> as.Date(df$Time, format = "%Y")
[1] "1999-11-28" "1999-11-28" "1999-11-28"

现在,我不知道您是否要使用plot()ggplot()ggplot2库……我不知道,没关系。 但是,您想指定 y 轴,您可以这样做。

暂无
暂无

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

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