简体   繁体   中英

In R, add a trace in a density plotly

Using the plotly package in R, I would like to do a desity plot. Actually, I need to add one more density line in my graph. I have a data with the income information of some public company by geographical region. Something like this

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

In a first moment, I analysed 5 and 6 regions' income with the following density plot

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) 

But, I want more than this. I would like to add the total income, ie the income of all regions. I tried something this

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)

Some solution for this?

Because you are not naming the parameters that you pass to add_trace , it interprets them as corresponding to the default parameter order. The usage of add_trace is

add_trace(p = last_plot(), ..., group, color, colors, symbol, symbols, size, data = NULL, evaluate = FALSE)

So, in your function call where you provide the data.frame df2 as the 2nd parameter, this is assumed to be correspond to the ... parameter, which must be a named list. You need to specify data = df2 , so that add_trace understands what this parameter is.

Lets generate some dummy data to demonstrate on

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

Now, (after calculating df and df2 as in your example):

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM