[英]In R, add a trace in a density plotly
使用R中的plotly包,我想做一个desity图。 实际上,我需要在图中添加一条密度线。 我有一个数据,其中包含按地区列出的一些上市公司的收入信息。 像这样
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)
一些解决方案?
由于您没有命名传递给add_trace
的参数,因此它将其解释为与默认参数顺序相对应。 add_trace
的用法是
add_trace(p = last_plot(),...,组,颜色,颜色,符号,符号,大小,数据= NULL,评估=假)
因此,在将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) )
现在,(在按照您的示例计算df
和df2
之后):
p <- plot_ly(df, x = x, y = y, color = cut) %>%
add_trace(data=df2, x = x, y = y, color = cut)
p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.