Using a ordered factor as timevar in Motion Chart

不羁的心 提交于 2019-12-12 00:32:36

问题


I have some data like this:

  time var1 var2 idvar
1   Q1    1    4     A
2   Q1    2    3     B
3   Q2    3    2     A
4   Q2    4    1     B

I need to make a MotionChart using each quarter (Q1 and Q2) as a time var. I have tried to make df$timean ordered factor, but it still gives me an error as the timevar needs to be in numeric or date format. Is there any workaround with this? My actual data spans several years and all 4 quarters of each year in the YYYYQn format, which I would not like to change.

The code I'm using in this example:

library(googleVis)

df = data.frame(time = c("Q1","Q1","Q2","Q2"),var1 = c(1,2,3,4),var2=c(4,3,2,1),idvar=c("A","B","A","B"))
df$time =  ordered(df$time)
g = gvisMotionChart(df,timevar="time",idvar="idvar")

The output is an error:

Error : The timevar has to be of numeric or Date format. Currently it is  orderedThe timevar has to be of numeric or Date format. Currently it is  factor

回答1:


Why did you converted to factor? the documentation says that timevar argument can't handle factor. It can handle character if and only if they are in a particular format, that is (for example): 2010Q1. Of course it can handle Date.

Here is my solution: I just create a new column with transform where I paste the year (which you have to know, otherwise you could use a proxy) to all the Q1, Q2 etc. it won't be hard by using recycling rules I think, here is just a little example. After that I convert that column into character.

transform(df, time2 = paste(2010, df$time, sep = "")) -> df1
df1$time2 <- as.character(df1$time2)

The df1 will be like that:

 df1
  time var1 var2 idvar  time2
1   Q1    1    4     A 2010Q1
2   Q1    2    3     B 2010Q1
3   Q2    3    2     A 2010Q2
4   Q2    4    1     B 2010Q2

After that you can use your code:

 g = gvisMotionChart(df1,timevar="time2",idvar="idvar")

produces this plot (with plot(g)):



来源:https://stackoverflow.com/questions/32146212/using-a-ordered-factor-as-timevar-in-motion-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!