1

I was wondering if I could get some help figuring out how to display the quantity of each bar when hovering over them. I made a bar chart to display shot frequency by shot type

 bones_count <- bones_22 %>%
  mutate( n = length(unique(typeAction))) %>%
  plot_ly( x = ~typeAction, y = ~n,
           hoverinfo = ~n)
  add_bars() %>%
  hide_guides()

If I convert to a tibble, n is 29 for all rows. I manually checked the quantities in my chart and they are accurate but I would like the actual quantities to display instead of 29, any suggestions would be greatly appreciated.

enter image description here

SamR
  • 8,826
  • 3
  • 11
  • 33
Dylan
  • 11
  • 1
  • Hi - welcome to SO. I have edited the formatting of your post but it is going to be difficult to help without a reproducible example of your data using `dput()`. Please see [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more details. – SamR Aug 02 '22 at 15:46

1 Answers1

0

Definitely a good idea to listen to the guidance from @SamR. You'll get faster answers that way.

If I understand what you're asking correctly, you're essentially looking for the value of y per bar to show in the hover content, correct? If that's what you wanted this should help.

You'll want to calculate these values before rendering your graph like I did with group and mutate.

library(tidyverse)
library(plotly)

data(animals, package = "ggfittext")

# only 6 rows, so double data to duplicate issue
ani = rbind(animals, animals) %>% as.data.frame() %>% 
  group_by(animal) %>% mutate(total = sum(mass)) # for the graph

plot_ly(ani, x = ~animal, y = ~mass, type = "bar",
        hovertext = ~total,
        hovertemplate = ("Total: %{hovertext}<extra></extra>"))

In this image, you see Total: 10000. In the data you'll see that there are two observations with the animal (well...fish) herring. Each of these observations indicates the mass is 5000.

enter image description here

If that's not what you meant or have questions, let me know.

Kat
  • 15,669
  • 3
  • 18
  • 51