使用“sparkTable”包装的多个系列的图表

时间:2011-12-21 10:04:01

标签: r sparktable

如果我理解正确,sparkTable包允许多种情节,但仅限于一个系列。因此,例如,如果我的数据集df如下所示:

variable  value   time
Level_1   34  1947
Level_1   38  1948
Level_1   17  1949
Level_1   61  1950
Level_1   19  1951
Level_1   80  1952
Level_1   57  1953
Level_1   66  1954

即。变量"值"改变"时间"在"变量"的各个层次上,我可以画出例如" value"的迷你图和条形图。对于不同级别的"变量"使用以下代码:

library(sparkTable)
content<-list()
content[['LinePlot']]<-newSparkLine()
content[['BarPlot']]<-newSparkBar()

varType<-rep("value",2)
df<-df[,c("variable","value","time")]
df$time<-as.numeric(as.character(df$time))
dat<-reshapeExt(df,idvar="variable",varying=list(2))
sparkTab<-newSparkTable(dat,content,varType)
plotSparkTable ( sparkTab , outputType = "html", filename = "t1")

但有没有办法在同一输出中绘制多个系列?例如,让我们说我想为&#34;值&#34;有一个迷你线,而另一个用于累积&#34;值&#34;系列随着时间的推移(由Cumulative_Value = ave(df$value, df$variable, FUN=cumsum)计算)

1 个答案:

答案 0 :(得分:6)

您的意思是在生成的sparkTable中添加额外的行吗?

编辑:OP希望添加额外的列,而不是行。

添加额外的列

要添加额外的列,您只需更新dfcontentvarType即可包含累计值。将以下内容添加到您的代码中:

# with the other lines defining content:
content[['Cumulative']] <- newSparkLine()

# add the following to your df
df$cumulative = ave(df$value, df$variable, FUN=cumsum)

# add the following to your varType definition
varType <- c('value','value','cumulative')

其余的可以保持不变。

第一行为您的表添加另一个火花线列,第二行计算cumulative列并将其添加到您的数据框,第三行告诉newSparkTable前两个图是用于valuecumulativedf列的最后一列。

enter image description here

添加额外的行

我知道的唯一方法(并不是很好)是在# make dummy data table with Levels 1 2 3, # years 1947:1966 for each, and # values being random from 1 to 100. years <- 1947:1966 n <- length(years) df <- data.frame( variable=sprintf('Level_%i',rep(1:3,each=n)), value=sample(100,3*n,replace=T), time=years ) # as before (setting up spark table) library(sparkTable) content<-list() content[['LinePlot']]<-newSparkLine() content[['BarPlot']]<-newSparkBar() # ** calculate cumulative value, and APPEND to the dataframe # There is a different cumulative line for *each* level. # Hence we need to make new factors # Level_1_cumulative, Level_2_cumulative, Level_3_cumulative cv <- ave(df$value, df$variable, FUN=cumsum) df2 <- rbind(df, data.frame( variable=sprintf('Level_%i_cumulative',rep(1:3,each=n)), value=cv, time=years )) # as before (make sparktable, but use df2 this time) dat<-reshapeExt(df2,idvar="variable",varying=list(2)) varType<-rep("value",2) sparkTab<-newSparkTable(dat,content,varType) plotSparkTable ( sparkTab , outputType = "html", filename = "t1") 添加额外的行,每行都对应累计值。

例如:

{{1}}

我最终得到这样的东西: enter image description here