2013-11-20 112 views
4

我在使用rCharts包中的rPlot函數了解如何自定義圖形時遇到了一些問題。說我有以下代碼rCharts Polychart:將水平線或垂直線添加到繪圖

#Install rCharts if you do not already have it 
#This will require devtools, which can be downloaded from CRAN 
require(devtools) 
install_github('rCharts', 'ramnathv') 

#simulate some random normal data 
x <- rnorm(100, 50, 5) 
y <- rnorm(100, 30, 2) 

#store in a data frame for easy retrieval 
demoData <- data.frame(x,y) 

#generate the rPlot Object 
demoChart <- rPlot(y~x, data = demoData, type = 'point') 

#return the object // view the plot 
demoChart 

這將生成一個情節,這是很好的,但我將如何去沿y軸添加水平線?例如,如果我想繪製一條表示平均y值的綠線,然後是與平均值相差+/- 3個標準差的紅線?如果有人知道一些文件,並可以指向我,那就太好了。但是,我唯一能找到的文檔是在polychart.js(https://github.com/Polychart/polychart2),我不是很清楚如何在這個R.

我已經做了一些挖掘應用到rChartsrPlot功能,我覺得像答案將與添加/修改rPlot對象內的layersparameter有關。

#look at the slots in this object 
demoChart$params$layers 

#doing this will return the following output (which will be different for 
#everybody because I didn't set a seed). Also, I removed rows 6:100 of the data. 

demoChart$params$layers 
[[1]] 
[[1]]$x 
[1] "x" 

[[1]]$y 
[1] "y" 

[[1]]$data 
     x  y 
1 49.66518 32.75435 
2 42.59585 30.54304 
3 53.40338 31.71185 
4 58.01907 28.98096 
5 55.67123 29.15870 


[[1]]$facet 
NULL 

[[1]]$type 
[1] "point" 

如果我想出來,我會發佈一個解決方案,但我會感激在此期間的任何幫助/建議!我在R中玩對象的經驗不多。我覺得這應該和ggplot2有一些相似之處,我也沒有太多的經驗。

感謝您的任何建議!

回答

3

您可以使用圖層將其他圖形疊加到您的rCharts圖上。將任何其他圖層的值作爲列添加到原始數據框中。使用copy_layer可以使用額外圖層中的data.frame中的值。

# Regression Plots using rCharts 
require(rCharts) 

mtcars$avg <- mean(mtcars$mpg) 
mtcars$sdplus <- mtcars$avg + sd(mtcars$mpg) 
mtcars$sdneg <- mtcars$avg - sd(mtcars$mpg) 

p1 <- rPlot(mpg~wt, data=mtcars, type='point') 

p1$layer(y='avg', copy_layer=T, type='line', color=list(const='red')) 
p1$layer(y='sdplus', copy_layer=T, type='line', color=list(const='green')) 
p1$layer(y='sdneg', copy_layer=T, type='line', color=list(const='green')) 

p1 

以下是幾個例子:一個從主rCharts website和其他顯示如何overlay a regression line