I am building a stacked bar chart in plotly and whenever I run my loop for add_trace, there is an issue as data of the previous trace seems to dissapear while names remain.
p = plot_ly( x = rownames(dist_data), y = as.numeric(dist_data[,1]), type = 'bar', name = colnames(dist_data)[1])%>%
layout(legend = list(x = 0.1, y = 0.9))
for ( j in 2:length(colnames(dist_data)))
{
p = add_trace(p, y = ~as.numeric(dist_data[,j]), type = 'bar',name = colnames(dist_data)[j]) %>%
layout( barmode = 'stack')
}
p
I am wondering whether there is something wrong in the loop. When trying manually for adding trace1, works fine. When adding trace 2 (j=3), trace1's values become automatically equal to trace2's value.
UPD: When using dplyr, I have issues with some other parts of my code. Is there a solution without it?
Thank you for the help,
You are overwriting p at each loop iteration. Try:
p = p %>% add_trace(y = ~as.numeric(dist_data[,j]), type = 'bar',name = colnames(dist_data)[j]) %>%
layout( barmode = 'stack')
2nd Edit: not sure why this is happening. It works if you reshape to a long format dataframe which is better practice than using a for loop:
mtcars %>%
mutate(id = rownames(.)) %>%
gather(key = "variable",value = "value",-id) %>%
plot_ly(x = ~id, y=~value, type="bar", color=~variable) %>%
layout(barmode = "stack")
Edit:
dist_data=mtcars
p = plot_ly( x = rownames(dist_data),
y = as.numeric(dist_data[,1]),
type = 'bar', name = colnames(dist_data)[1]) %>%
layout(legend = list(x = 0.1, y = 0.9))
for ( j in 2:length(colnames(dist_data))){
p = add_trace(p, y = ~as.numeric(dist_data[,j]),
type = 'bar',name = colnames(dist_data)[j]) %>%
layout( barmode = 'stack')
}
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.