2
votes

I am trying to make a very simple bar chart with ggplot2 and then to turn it into interactive graph with the ggplotly function from the plotly package. The final graph looks ok, but the values rendered in the hover text are not good. Actually, it renders stacked values instead of individual values.

Here is a reproducible example :

#data
dataf = data.frame(Espece = c("A","A","B","B","C","C"),
                   Type = c("A","B","A","B","A","B"),
                   Value = c(2,2,5,1,6,0))
#ggplot
gg = ggplot(dataf, aes(x = Espece, y = Value, fill = Type)) + 
  geom_bar(stat = "identity") +
  theme(legend.position = "none") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

#plotly
p <- ggplotly(gg)
p

enter image description here

As you can see on the picture, the value for Espece A, type B is 4 whereas it should be 2.

Do you have any idea how I can fix this ?

1
You use dataf2 in ggplot while creating dataf just before. Is dataf2 a new data frame or equal to dataf ? In dataf, the value for Espece A, type B is 4. - bVa

1 Answers

0
votes

When you print the ggplot graphic it looks fine. So maybe it's one of the bugs. Until it's fixed maybe you could use this alternative:

library(dplyr)
datafA <- dataf %>% filter(Type == "A")
datafB <- dataf %>% filter(Type == "B")

p <- plot_ly(data=datafA,
  x = Espece,
  y = Value,
  type = "bar",
  hoverinfo="text",
  text = paste("Espece = ", datafA$Espece, "<br>Value = ", datafA$Value, "<br>Type = ", datafA$Type),
  color = Type, colors = "red"
)
p


p2 <- add_trace(
  p,
  data=datafB,
  x = Espece,
  y = Value,
  type = "bar",
  hoverinfo="text",
  text = paste("Espece = ", datafB$Espece, "<br>Value = ", datafB$Value, "<br>Type = ", datafB$Type),
  color = Type, colors = "blue"
)
p2

layout(p2, barmode = "stack", showlegend = FALSE)

enter image description here