Reputation: 707
I'm trying to plot two different set of data on the same figure, using two àdd_trace
commands. I specify a different colorscales for each, but the second one is ignored , so my second scatter plot has the same color gradient than the first one. How can I fix this ?
I tried the solution here, but it doesn't work (I got a warning saying 'scatter' objects don't have these attributes: 'colorscale'
).
My code (with a dataframe with random numbers for testing) :
library(plotly)
library(FactoMineR)
n <- 10 ; m <- 20 ; reps <- 6
a <- as.data.frame(cbind(matrix(seq_len(m), n, m/n),
replicate(reps, sample(c(0, 1), n, replace = TRUE))))
res.pca = PCA(a, scale.unit=TRUE, graph=F, axes=c(1,2))
ind <- as.data.frame(res.pca$ind$coord)
cos2 <- as.data.frame(res.pca$ind$cos2)
var <- as.data.frame(res.pca$var$coord)
cos2_v <- as.data.frame(res.pca$var$cos2)
biplot <- plot_ly(ind) %>%
add_trace(x=ind[,1],
y=ind[,2],
type='scatter',
text=rownames(a),
textposition='top',
mode="markers+text",
color=cos2[,1],
colors="OrRd",
marker=list(symbol=27, size=11)) %>%
add_trace(var,
x=var[,1],
y=var[,2],
type = 'scatter',
text=colnames(a),
textposition='top',
mode="markers+text",
color=cos2_v[,1],
colors="BuGn",
marker=list(symbol=4, size=11))
Thanks in advance (the actual result is on the picture below).
Upvotes: 2
Views: 1511
Reputation: 441
This works. If you do something custom you have to format the arguments according to plotly::schema()
. The colors
argument in plotly is a helper to streamline the more complicated plotly.js
syntax. Note how color
and all the other marker arguments have to be within a list called marker
, under which you have to manually format both the colorscale
(to get the colors you want) and the colorbar
(to get the colorscale positioned correctly). Note also that the legend is for the shape, while the colorscale is for the color (confusingly the colorscale is not the legend).
library(plotly)
library(FactoMineR)
n <- 10 ; m <- 20 ; reps <- 6
a <- as.data.frame(cbind(matrix(seq_len(m), n, m/n),
replicate(reps, sample(c(0, 1), n, replace = TRUE))))
res.pca = PCA(a, scale.unit=TRUE, graph=F, axes=c(1,2))
ind <- as.data.frame(res.pca$ind$coord)
cos2 <- as.data.frame(res.pca$ind$cos2)
var <- as.data.frame(res.pca$var$coord)
cos2_v <- as.data.frame(res.pca$var$cos2)
biplot <- plot_ly(ind,showlegend=F) %>%
add_trace(x=ind[,1],
y=ind[,2],
type='scatter',
text=rownames(a),
textposition='top',
mode="markers+text",
marker=list(symbol=27, size=11
,color=cos2[,1]
,colorscale=list(
list(0,RColorBrewer::brewer.pal(3,'OrRd')[1])
,list(1,RColorBrewer::brewer.pal(3,'OrRd')[3])
)
,colorbar=list(yanchor='bottom',len=.5)
)) %>%
add_trace(x=var[,1],
y=var[,2],
type='scatter',
text=colnames(a),
textposition='top',
mode="markers+text",
marker=list(symbol=4, size=11
,color=cos2_v[,1]
,colorscale=list(
list(0,RColorBrewer::brewer.pal(3,'BuGn')[1])
,list(1,RColorBrewer::brewer.pal(3,'BuGn')[3])
)
,colorbar=list(yanchor='top',len=.5)
))
biplot
Upvotes: 2