简体   繁体   English

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

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

i have a dataset given with:我有一个数据集:

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

.... and so on. .... 等等。 Now I would like to plot this dataframe with Time being on the x-axis and y being the Value.现在我想 plot 这个 dataframe 时间在 x 轴上,y 是值。 But the problem I face is I dont know how to plot the Time.但我面临的问题是我不知道如何 plot 时间。 Because it is not given in month/date/year.因为它没有在月/日/年中给出。 If that would be the case I would just code as.Date( format = "%m%d%y") .如果是这种情况,我只需编码as.Date( format = "%m%d%y") I am not allowed to change the quarterly name.我不允许更改季度名称。 So when I plot it, it should stay that way.所以当我 plot 它时,它应该保持这种状态。 How can I do this?我怎样才能做到这一点?

Thank you in advance!先感谢您!

Assuming DF shown in the Note at the end, convert the Time column to yearqtr class which directly represents year and quarter (as opposed to using Date class) and use scale_x_yearqtr .假设最后的注释中显示 DF,将 Time 列转换为yearqtr class 直接表示年份和季度(而不是使用Date类)并使用scale_x_yearqtr See ?scale_x_yearqtr for more information.有关更多信息,请参阅?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)

(continued after graphics) (图后续) 截屏

It would also be possible to convert it to a wide form zoo object with one column per country and then use autoplot .也可以将其转换为每个国家一列的宽格式动物园 object,然后使用autoplot Using DF from the Note below:使用下面注释中的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)

Note笔记

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

Using ggplot2:使用 ggplot2:

library(ggplot2)

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

在此处输入图像描述

I know other people have already answered, but I think this more general answer should also be here.我知道其他人已经回答了,但我认为这个更一般的答案也应该在这里。

When you do as.Date() , you can only do the beginning.当你做as.Date()时,你只能做开始。 I tried it on your data frame (I called it df ), and it worked:我在您的数据框上尝试了它(我称之为df ),它起作用了:

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

Now, I don't know if you want to use plot() , ggplot() , the ggplot2 library... I don't know that, and it doesn't matter.现在,我不知道您是否要使用plot()ggplot()ggplot2库……我不知道,没关系。 However you want to specify the y axis, you can do it this way.但是,您想指定 y 轴,您可以这样做。

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

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