[英]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.