Search code examples
rplotlyheatmapaxis-labels

Coloring the axis tick text by multiple colors


I'm trying to plot a heatmap using R's plotly package, where I'd like to have specific colors to specific labels of the y-axis tick text.

Here's an example dataset:

set.seed(1)
df <- reshape2::melt(matrix(rnorm(100),10,10,dimnames = list(paste0("G",1:10),paste0("S",1:10))))

And here's what I'm trying:

library(plotly)
library(dplyr)
plot_ly(z=c(df$value),x=df$Var2,y=df$Var1,colors=grDevices::colorRamp(c("darkblue","gray","darkred")),type="heatmap",colorbar=list(title="Scaled Value",len=0.4)) %>%
  layout(yaxis=list(title=list(color=c(rep("darkred",5),rep("darkblue",5)))))

It's not working since I'm getting: enter image description here

Changing: yaxis=list(title=list(color=c(rep("darkred",5),rep("darkblue",5))))

To: yaxis=list(title=list(color=list(c(rep("darkred",5),rep("darkblue",5)))))

Or: yaxis=list(title=list(tickcolor=c(rep("darkred",5),rep("darkblue",5))))

Or: yaxis=list(title=list(tickcolor=list(c(rep("darkred",5),rep("darkblue",5)))))

Doesn't seem to help.

Any idea?


Solution

  • A similar question with a different setup has been asked and answered for Python here: Setting a different font color for specific x axis ticks. Below is my best attempt with your setup for R.

    Plot:

    enter image description here

    Code:

    library(plotly)
    library(dplyr)
    
    # data
    set.seed(1)
    df <- reshape2::melt(matrix(rnorm(100),10,10,dimnames = list(paste0("G",1:10),paste0("S",1:10))))
    
    # plotly setup
    p1 <- plot_ly(z=c(df$value),x=df$Var2,y=df$Var1,colors=grDevices::colorRamp(c("darkblue","gray","darkred")),
                  type="heatmap",colorbar=list(title="Scaled Value",len=0.4)) 
    
    p2 <- p1 %>% add_trace(xaxis='x2', showscale=FALSE)
    
    p3 <- p2  %>% layout(xaxis=list(range=list(0,9),
                                    tickvals=list(0,1,2,3,4),
                                    tickfont=list(color='red')),
                         xaxis2=list(range=list(0,9), overlaying='x',
                                     ticktext = list('s9', 's10'),
                                     tickvals=list(5, 6, 7, 8, 9),
                                     tickfont=list(color='blue')))
    # plot it
    p3