Reputation: 8454
I create the barchart below with a custom hovertemplate but instead of my text
I get a "text"
when I hover over the bars.
Cum4c<-structure(list(Country = c("United States Of America", "Mexico",
"United Kingdom", "Brazil", "Germany"), Deaths = c(91765, 31887,
31134, 29081, 22546), lab = c("91,765", "31,887", "31,134", "29,081",
"22,546")), row.names = c(NA, -5L), class = c("tbl_df", "tbl",
"data.frame"))
fig1 <- plot_ly()%>%
add_bars(data = Cum4c, x = ~Country, y = ~Deaths,
text = ~ paste("<b>Country:</b>", Country, "<br><b>Deaths:</b>", lab),
hovertemplate = paste('%{text}<extra></extra>'),
colors = c("#60ab3d","#6bbabf","#c4d436","#3e5b84","#028c75"),
color = ~Country
)
fig1 <- fig1 %>% layout(showlegend = TRUE,title=list(text="worldwide,by selected territories and period",x = 0,y=1,font=list(size=10)),
font = list(color = '#a2a2a2'),
legend=list(y=1.2,x=0,title=list(text='<b> Top 5 </b>')),
yaxis = list(fixedrange = TRUE,title="",
#dtick = 250000
showgrid = T,gridcolor = "#a2a2a2", showline = FALSE, showticklabels = TRUE, domain= c(0, 0.85)),
xaxis = list(fixedrange = TRUE,title="",zeroline = FALSE, showline = T,showticklabels = F,tickangle=45, showgrid = FALSE))%>%
config(modeBarButtonsToRemove = c('toImage',"zoom2d","toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian","drawline","autoScale2d" ,"resetScale2d","zoomIn2d","zoomOut2d","pan2d",'select2d','lasso2d'))%>%
config(displaylogo = FALSE)
fig1
Upvotes: 0
Views: 376
Reputation: 125797
There are two approaches to achieve your desired result:
Get rid of text
and instead use hovertemplate = ~paste("<b>Country:</b>", Country, "<br><b>Deaths:</b>", lab)
Get rid of hovertemplate
and use hoverinfo = 'text'
instead.
Both approaches will give you the same result.
library(plotly)
fig1 <- plot_ly() %>%
add_bars(
data = Cum4c, x = ~Country, y = ~Deaths,
hovertemplate = ~paste("<b>Country:</b>", Country, "<br><b>Deaths:</b>", lab),
colors = c("#60ab3d", "#6bbabf", "#c4d436", "#3e5b84", "#028c75"),
color = ~Country
)
fig1
fig1 <- plot_ly() %>%
add_bars(
data = Cum4c, x = ~Country, y = ~Deaths,
text = ~ paste("<b>Country:</b>", Country, "<br><b>Deaths:</b>", lab),
hoverinfo = 'text',
colors = c("#60ab3d", "#6bbabf", "#c4d436", "#3e5b84", "#028c75"),
color = ~Country
)
fig1
Upvotes: 2