3
votes

I have been using example on custom hover text (https://plot.ly/r/text-and-annotations/) to change hover text in barplots i'm working on. If my barplot only includes one stacked bar the new hover text doesn't show. Example (it's in the last plot where the hoverinfo is missing):

library(plotly)
year <- c(2015,2015,2016,2016)
type <- c('A','B','A','B')
perc <- c(10,90,20,80)

data <- data.frame(year,type,perc)

# Plot all the data ... default hoverinfo shown
plot_ly(data,x=~year,y=~perc,color=~type) %>% 
  add_bars()%>% 
  layout(barmode = "stack")

# Plot all the data ... custom hoverinfo shown
plot_ly(data,x=~year,y=~perc,color=~type,
  text = ~paste('Type',type,': ',perc,'%'),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack")

# Plot part of the data ... default hoverinfo shown
plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type) %>% 
  add_bars()%>% 
  layout(barmode = "stack")

# Plot part of the data ... custom hoverinfo does not appear!
plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type,
  text = ~paste('Type',type,': ',perc,'%'),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack")

Using R version 3.3.2 and plotly version 4.5.6.

1

1 Answers

2
votes

Got some help and the solution is to define the text as a list.

plot_ly(data[data$year == 2015,],x=~year,y=~perc,color=~type,
  text = ~list(paste('Type',type,': ',perc,'%')),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack")

This works as long as I know there is only one bar and the order of the ~type is the same throughout the dataset. If I change the types to

type <- c('A','B','B','A')

and run

data <- data.frame(year,type,perc)
plot_ly(data[data$year == 2016,],x=~year,y=~perc,color=~type,
      text = ~list(paste(year,'Type',type,': ',perc,'%')),hoverinfo = 'text') %>% 
  add_bars()%>% 
  layout(barmode = "stack") 

I don't get the right order of hoverinfo. So this is not the perfect solution.