Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating R plotly legend

Probably an easy question:

Trying to use plotly to produce a scatter plot and customize the legend.

Here's my data:

require(plotly)
set.seed(1)

my.df <- data.frame(id=LETTERS[sample(26,100,replace=T)],x=rnorm(100),y=rnorm(100),sig=runif(100,0,1),stringsAsFactors = F)

In my case I'm calling this with the column indices, thus:

x.idx <- which(colnames(my.df) == "x")
y.idx <- which(colnames(my.df) == "y")
sig.idx <- which(colnames(my.df) == "sig")
sig.name <- "p-value"

And what I want to do is have the legend title be sig.name and make the legend smaller than the default size. So I'm trying:

p <- plot_ly(x=~my.df[,x.idx],y=~my.df[,y.idx],color=~my.df[,sig.idx],text=~my.df$id,colors=c("darkblue","darkred")) %>% add_annotations(text=sig.name,xref="paper",yref="paper",xanchor="left",x=1,y=1,yanchor="top",legendtitle=T,showarrow=FALSE) %>% layout(legend=list(y=0.8,yanchor="top"),xaxis=list(title=colnames(my.df)[x.idx],zeroline=F),yaxis=list(title=colnames(my.df)[y.idx],zeroline=F))

Which gives me: enter image description here

Not exactly what I want.

So:

  1. How do I delete the default legend title?

  2. How do I make the legend smaller?

like image 811
dan Avatar asked Jun 20 '26 18:06

dan


1 Answers

You are probably looking for colorbar: len and colorbar: title. enter image description here

plot_ly(type = 'scatter', 
        mode = 'markers', 
        x = ~my.df[,x.idx],
        y = ~my.df[,y.idx],
        color = ~my.df[,sig.idx],
        text =~my.df$id,
        colors = c("darkblue","darkred"),
        marker = list(colorbar = list(len = 0.2, 
                                      title = sig.name)
        )
)
like image 109
Maximilian Peters Avatar answered Jun 23 '26 08:06

Maximilian Peters