2016-07-04 101 views
0

使用R中的plotly包,我想做一个平面图。实际上,我需要在图形中添加一条密度线。我有一个地区的一些上市公司的收入信息的数据。这样在R中,在一个密度图中添加一条迹线

head(data) 
id income region 
    1  4556  1 
    2  6545  1 
    3 65465  2 
    4 54555  1 
    5 71442  2 
    6  5645  6 

东西在第一关键时刻,我分析了5对6各地区和下面的密度图

reg56<- data[data$region %in% c(5,6) , ] 
dens <- with(reg56, tapply(income, INDEX = region, density)) 
df <- data.frame(
x = unlist(lapply(dens, "[[", "x")), 
y = unlist(lapply(dens, "[[", "y")), 
cut = rep(names(dens), each = length(dens[[1]]$x)) 
) 

# plot the density 
p<- plot_ly(df, x = x, y = y, color = cut) 

收入不过,我想比这更多。我想增加总收入,即所有地区的收入。我试过这样的东西

data$aux<- 1 
dens2 <- with(data, tapply(income, INDEX = 1, density)) 
df2 <- data.frame(
x = unlist(lapply(dens2, "[[", "x")), 
y = unlist(lapply(dens2, "[[", "y")), 
cut = rep(names(dens2), each = length(dens2[[1]]$x))) 

p<- plot_ly(df, x = x, y = y, color = cut) 
p<- add_trace(p, df2, x = x, y = y, color = cut) 
p 
Error in FUN(X[[i]], ...) : 
'options' must be a fully named list, or have no names (NULL) 

有些解决方案呢?

回答

1

因为您没有命名您传递给add_trace的参数,所以它将它们解释为对应于默认参数顺序。的add_trace用法是

add_trace(p值= last_plot(),...,组,颜色,颜色,符号,符号, 大小,数据= NULL,评价= FALSE)

因此,在您提供data.frame df2作为第二个参数的函数调用中,假定这对应于参数...,该参数必须是一个命名列表。您需要指定data = df2,以便add_trace了解此参数。

让我们产生了一些假的数据来证明对

library(plotly) 
set.seed(999) 
data <- data.frame(id=1:500, income = round(rnorm(500,50000,15000)), region=sample(6,500,replace=T)) 

现在,(计算dfdf2在你的例子后):

p <- plot_ly(df, x = x, y = y, color = cut) %>% 
    add_trace(data=df2, x = x, y = y, color = cut) 
p 

enter image description here

相关问题