Unable to change the labels on the tooltip - r

I am using plotly package to make a heatmap. However, the tooltips show "x,y,z" instead of "Base, weekday, count". Please guide me on how to fix this issue as I'm new to plotly package. My code is:
p<-plot_ly(x=colnames(df_base_dayofweek_m), y=rownames(df_base_dayofweek_m), z = df_base_dayofweek_m, type = "heatmap") %>%
layout(margin = list(l=120))
p <- p %>% layout(title = 'Ride count for different bases',margin=m,
titlefont = list(size = 38, color = "black", family = "Calibri"),
xaxis = list(title = 'Bases',tickfont = list(size = 15), ticktext = sprintf("<b>%s</b>",
levels(factor(df_base_dayofweek_label$Base))),
tickvals = levels(factor(df_base_dayofweek_label$Base)),
titlefont = list(color = "black",size = 28, family = "Arial")),
yaxis = list(title = 'Weekday',tickfont = list(size = 15),ticktext = sprintf("<b>%s</b>",
levels(factor(df_base_dayofweek_label$dayofweek))),
tickvals = levels(factor(df_base_dayofweek_label$dayofweek)),
titlefont = list(color = "black",size = 28,family = "Arial")))
p
Thanks!

As you haven't provided any data I'm taking an example from here.
You can use plot_lys argument hovertemplate to modify the hoverinfo:
library(plotly)
fig <- plot_ly(z = volcano,
type = "heatmap",
hovertemplate = "Base: %{x}<br>Weekday: %{y}<br>Count: %{z}<extra></extra>")
fig

Related

Setting colours in plotly R is not working (factors) in add markers

I'm trying to set the colour in R for "points" or markers in plotly with a custom palette. It doesn't work. I'm also trying to add a title to the graph, but it won't appear. In addition, I'd like to remove some elements of the legend (like the extra "z") and add a title to the legend elements. Nothing seems to work, even if it is present in the code.
library(plotly)
library(tidyverse)
set.seed(123456)
pal <- c("black", "orange", "darkgreen", "pink")
pal <- setNames(pal, levels(as.factor(c("gr1","gr2","gr3","gr4"))))
linedat = data.frame(x = rep(mean(1:50),2),
y = rep(mean(1:50),2),
z = c(0,1))
zoom = 3
pg = plotly::plot_ly(x = 1:50,
y = 1:50,
z = outer(1:50,1:50,"+")/100) %>%
add_surface(contours = list(
z = list(show = TRUE, start = 0, end = 1, size = 0.05)),
opacity = 1) %>%
add_markers(x = rnorm(50,25,5),
y = rnorm(50,25,5),
marker = list(opacity = 0.9),
type="scatter3d",
mode = "markers",inherit = FALSE,
colors = pal,
color = as.factor(sample(1:4,50,replace = T)),
z = rbinom(50,1,.5)) %>%
layout(scene=list(title = "Title won't show up????",
xaxis = list(title = 'trait1'),
yaxis = list(title = 'trait1',autorange = "reversed"),
camera = list(eye = list(x = cos(0.8*pi)*zoom, y = sin(pi*1.3)*zoom, z= 2.00)),
legend = list(title=list(text='<b> Groups </b>')))) %>%
add_trace(data=linedat, x=~x, y=~y, z=~z,
type="scatter3d", mode="lines",
line = list(color = pal[1],
width = 14),name = "Avg. data1")%>%
add_trace(data=linedat, x=~x+20, y=~y+20, z=~z,
type="scatter3d", mode="lines",
line = list(color = pal[4],
width = 14),name = "Avg. data2")
pg
See how here I'm able to set the colour of the points, but I'm not able to get the names of the colours to show in the legend (I modified the code to match what #Kat suggested):
library(plotly)
library(tidyverse)
set.seed(123456)
pal <- c("black", "orange", "darkgreen", "pink")
pal <- setNames(pal, levels(as.factor(c("gr1","gr2","gr3","gr4"))))
linedat = data.frame(x = rep(mean(1:50),2),
y = rep(mean(1:50),2),
z = c(0,1))
zoom = 3
pg = plotly::plot_ly(x = 1:50,
y = 1:50,
z = outer(1:50,1:50,"+")/100) %>%
add_surface(contours = list(
z = list(show = TRUE, start = 0, end = 1, size = 0.05)),
opacity = 1, colorbar = list(title = "Only one Z")) %>%
add_markers(x = rnorm(50,25,5),
y = rnorm(50,25,5),
marker = list(color = pal[as.factor(sample(1:4,50,replace = T))],opacity = 0.9),
type="scatter3d",
mode = "markers",inherit = FALSE,
colors = pal,
z = rbinom(50,1,.5)) %>%
layout(title = "Title that won't show",
margin = list(t = 40),
legend = list(title = list(
text = "<br>Legends deserve names, too")),
scene=list(xaxis = list(title = 'trait1'),
yaxis = list(title = 'trait1',autorange = "reversed"),
camera = list(eye = list(x = cos(0.8*pi)*zoom,
y = sin(pi*1.3)*zoom, z= 2.00)))) %>%
add_trace(data=linedat, x=~x, y=~y, z=~z,
type="scatter3d", mode="lines",
line = list(color = pal[1],
width = 14),name = "Avg. data1")%>%
add_trace(data=linedat, x=~x+20, y=~y+20, z=~z,
type="scatter3d", mode="lines",
line = list(color = pal[4],
width = 14),name = "Avg. data2");pg
Your original plot_ly call and add_trace calls can remain as is. I've included the changes needed for the layout call and added the call needed for colorbar.
The layout first.
layout(title = "Title that won't show", # <------ give my plot a name
margin = list(t = 40), # don't smash that title, either
legend = list(title = list(
text = "<br>Legends deserve names, too")), # <--- name my legend
scene=list(title = "Title won't show up????", # <- this can go away
xaxis = list(title = 'trait1'),
yaxis = list(title = 'trait1',autorange = "reversed"),
camera = list(eye = list(x = cos(0.8*pi)*zoom,
y = sin(pi*1.3)*zoom, z= 2.00)),
legend = list(title=list(text='<b> Groups </b>')))) %>%
colorbar(title = "Only one Z") # <--- give me one z colorbar title
(Some colors are different in the image; I didn't realize I had the pal object...sigh)
Update
This addresses your additional questions.
First, I'm not getting an error from the method in which I title the color bar. You'll have to share what error you're getting.
I didn't realize that it was ignoring the colors you set in markers, either. The easiest way to address this is to call that trace first. Since nothing else was declared within markers, I called opacity outside of the list, but it's fine the way you have it.
First, I commented out the setNames call, because that won't work for the marker's trace and it doesn't matter to the other traces.
library(plotly)
set.seed(123456)
pal <- c("black", "orange", "darkgreen", "pink")
# pal <- setNames(pal, levels(as.factor(c("gr1","gr2","gr3","gr4"))))
linedat = data.frame(x = rep(mean(1:50),2),
y = rep(mean(1:50),2),
z = c(0,1))
zoom = 3
I made plot_ly() empty and put all the data for the surface in that trace. I also added inherit = false so that the layout could go at the end without the data errors.
set.seed(123456)
pg = plotly::plot_ly() %>%
add_trace(inherit = F,
x = rnorm(50,25,5),
y = rnorm(50,25,5),
type="scatter3d",
mode = "markers",
opacity = .8,
colors = pal,
color = as.factor(sample(1:4, 50, replace = T)),
z = rbinom(50,1,.5)) %>%
add_surface(x = 1:50,
y = 1:50,
z = outer(1:50,1:50,"+")/100,
colorscale = "Viridis",
contours = list(
z = list(show = TRUE, start = 0, end = 1, size = 0.05)),
opacity = 1) %>%
add_trace(data=linedat, x=~x, y=~y, z=~z,
type="scatter3d", mode="lines",
line = list(color = pal[1],
width = 14),name = "Avg. data1", inherit = F) %>%
add_trace(data=linedat, x=~x+20, y=~y+20, z=~z,
type="scatter3d", mode="lines",
line = list(color = pal[4],
width = 14),name = "Avg. data2", inherit = F) %>%
The last part is the layout, but this is not different than my original answer.
layout(title = "Title that won't show", # <------ give my plot a name!
margin = list(t = 40), # don't smash that title, either
legend = list(title = list(
text = "<br>Legends deserve names, too"),
tracegroupgap = 350), # <--- name my legend!
scene=list(title = "Title won't show up????", # <--- this can go away!
xaxis = list(title = 'trait1'),
yaxis = list(title = 'trait1',autorange = "reversed"),
camera = list(eye = list(x = cos(0.8*pi)*zoom,
y = sin(pi*1.3)*zoom, z= 2.00)),
legend = list(title=list(text='<b> Groups </b>')))) %>%
colorbar(title = "Only one Z") # <--- give me one z for the title!
pg

How to remove the whitespace surrounding a plotly bullet chart in R

I have created the following bullet chart in R
library(plotly)
fig<-plot_ly()
fig <- fig %>%
add_trace(
type = "indicator",
mode = "number+gauge+delta",
value = 35,
delta = list(reference = 100),
domain = list(x = c(0.25, 1), y = c(0.4, 0.6)),
title = list(text = "Avalue"),
gauge = list(shape = "bullet",axis = list(range = list(NULL, 100)),threshold = list(
line = list(color = "black", width= 2), thickness = 0.75,value = 55),steps = list(
list(range = c(0, 25), color = "red"),
list(range = c(25, 50), color = "blue"),
list(range = c(50, 75), color = "green"),
list(range = c(75, 100), color = "grey")),
bar = list(color = "grey")))
How do I remove the whitespace around the chart. And is there a way I can adjust the length of the chart
You should change your values for your domain in the add_trace. I changed the y to FALSE and x to a different range, which results in the following plot:
library(plotly)
fig<-plot_ly()
fig <- fig %>%
add_trace(
type = "indicator",
mode = "number+gauge+delta",
value = 35,
delta = list(reference = 100),
domain = list(x = c(0.1, 1), y = FALSE),
title = list(text = "Avalue"),
gauge = list(shape = "bullet",axis = list(range = list(NULL, 100)),threshold = list(
line = list(color = "black", width= 2), thickness = 0.75,value = 55),steps = list(
list(range = c(0, 25), color = "red"),
list(range = c(25, 50), color = "blue"),
list(range = c(50, 75), color = "green"),
list(range = c(75, 100), color = "grey")),
bar = list(color = "grey")))
fig
Output:
As you can see, the whitespace is way less.

R Disable layer in Plotly

I have a plot with multiple lines and would like to initialize it with just some layers active. Is it possible? Here is an example of what the data looks like:
set.seed(101)
df <- data.frame(x = seq(1,20,1),
y1 = runif(20),
y2 = runif(20),
y3 = runif(20),
y4 = runif(20))
plot_ly(df, x = ~x) %>%
add_lines(y = ~y1, name='y1', line = list(color = 'rgba(255,0,0,1')) %>%
add_lines(y = ~y2, name='y2', line = list(color = 'rgba(0,255,0,1')) %>%
add_lines(y = ~y3, name='y3', line = list(color = 'rgba(106,90,205,1')) %>%
add_lines(y = ~y4, name='y4', line = list(color = 'rgba(0,0,255,1')) %>%
layout(
xaxis = list(title = "x", domain = c(0,1), tickmode = 'auto'),
yaxis = list(title = 'y', side = "left", color = "black", position = 0,
anchor = 'free', range = c(0,1), dtick = 1),
showlegend = T
)
What I want is to generate a plot with all lines, but e.g. with y3 and y4 off and still allow the user to turn it on (this plot is part of a shiny app).
Is it even possible?
Thanks!
You need to set visible = "legendonly" for the traces you want to hide:
library(plotly)
set.seed(101)
df <- data.frame(x = seq(1,20,1),
y1 = runif(20),
y2 = runif(20),
y3 = runif(20),
y4 = runif(20))
plot_ly(df, x = ~x) %>%
add_lines(y = ~y1, name='y1', line = list(color = 'rgba(255,0,0,1')) %>%
add_lines(y = ~y2, name='y2', line = list(color = 'rgba(0,255,0,1')) %>%
add_lines(y = ~y3, name='y3', line = list(color = 'rgba(106,90,205,1'), visible = "legendonly") %>%
add_lines(y = ~y4, name='y4', line = list(color = 'rgba(0,0,255,1'), visible = "legendonly") %>%
layout(
xaxis = list(title = "x", domain = c(0,1), tickmode = 'auto'),
yaxis = list(title = 'y', side = "left", color = "black", position = 0,
anchor = 'free', range = c(0,1), dtick = 1),
showlegend = TRUE
)
To get more information regarding the available trace attributes use:
schema()
and navigate as follows:
object ► traces ► scatter ► attributes

Add hover text or text annotation in plotly gauge chart

Can we add hovertext or text annotation in a plotly gauge chart? For example in my plot below I want to add in the green area hover or text or both "Uptake first dose%: 19.8" and in the gray area "Not vaccinated (%):80.2"
library(plotly)
fig <- plot_ly(
type = "indicator",
mode = "gauge+number+delta",
value = 19.8,
title = list(text = "Uptake first dose %", font = list(size = 24)),
delta = list(reference = 70, increasing = list(color = "gray")),
gauge = list(
axis = list(range = list(NULL, 100), tickwidth = 1, tickcolor = "lightgreen"),
bar = list(color = "lightgreen"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(
list(range = c(0, 50), color = "lightgreen"),
list(range = c(20, 100), color = "gray")),
threshold = list(
line = list(color = "black", width = 4),
thickness = 0.75,
value = 70)))
fig <- fig %>%
layout(
margin = list(l=20,r=30),
paper_bgcolor = "lavender",
font = list(color = "darkblue", family = "Arial"))
fig
You can add annotations but I couldn't find a way to get the hovertext without an annotation.
fig <- plotly::plot_ly(
type = "indicator",
mode = "gauge+number+delta",
value = 19.8,
title = list(text = "Uptake first dose %", font = list(size = 24)),
delta = list(reference = 70, increasing = list(color = "gray")),
gauge = list(
axis = list(range = list(NULL, 100), tickwidth = 1, tickcolor = "lightgreen"),
bar = list(color = "lightgreen"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(
list(range = c(0, 50), color = "lightgreen"),
list(range = c(20, 100), color = "gray")),
threshold = list(
line = list(color = "black", width = 4),
thickness = 0.75,
value = 70)))
fig <- fig %>%
plotly::layout(
margin = list(l=20,r=30),
paper_bgcolor = "lavender",
font = list(color = "darkblue", family = "Arial"),
annotations = list(x = 0.05, y = 0.3, text = "19.8%",
hovertext = "Your Text",
showarrow = FALSE))
fig
You could also use add_annotations if you want to add multiples.
See https://plotly.com/r/text-and-annotations/

Prevent Overlapping of labels in Plotly

I am plotting bubble chart using Plotly in R. But when I give labels using add_annotations labels overlap and its very difficult to read them. how to prevent this overlapping in plotly. I have tried "geom_label_repel" but its not working with plotly as it gives error.
My Code is
plot_ly(bubbleChartData, x = ~Category1, y = ~Category2, type = 'scatter', mode = 'markers', size = ~BubbleSize,
color = ~Category3, colors = brewer.pal(8,"Dark2"),
marker = list( sizemode = 'diameter'), text=~Category4) %>%
add_annotations( showarrow=F,xanchor="right",xref = "x",ax = 20,
ay = -40,
yref = "y",x = ~Category1, y = ~Category2, text=~Category4,font = list(size = 10))%>%
layout(title = '',font=list(size=10),
xaxis = list(
title = "",
showgrid=FALSE,
showline=FALSE,
tickfont = list(
size = 16,
color = 'rgb(0,0,0)'),
titlefont = list(
size = 18,
color = 'rgb(0,0,0)')),
yaxis = list(
title = "",
showgrid=FALSE,
showline=FALSE,
titlefont = list(
size = 18,
color = 'rgb(0,0,0)'),
tickfont = list(
size = 16,
color = 'rgb(0,0,0)')),
showlegend = F)

Resources