【问题标题】:Stacked bar issue with new version of plotly新版本 plotly 的堆积条问题
【发布时间】:2016-04-20 10:27:32
【问题描述】:

我正在尝试使用 ggplot2 制作一个非常简单的条形图,然后使用 plotly 包中的 ggplotly 函数将其变成交互式图表。 最终的图表看起来不错,但是在悬停文本中呈现的值并不好。实际上,它呈现的是堆叠值而不是单个值。

这是一个可重现的例子:

#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

正如您在图片上看到的,Espece A, type B 的值为 4,而应该是 2。

你知道我该如何解决这个问题吗?

【问题讨论】:

  • 您在 ggplot 中使用 dataf2 之前创建 datafdataf2 是新数据框还是等于 dataf ?在dataf 中,Espece A、B 类型的值为 4。

标签: r ggplot2 plotly


【解决方案1】:

当您打印 ggplot 图形时,它看起来很好。所以也许这是错误之一。在它修复之前,也许你可以使用这个替代方案:

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)

【讨论】:

  • 嗨@MLavoie,非常感谢您的回答。我想过那个解决方案,但问题是,这只是一个例子,在真实数据中,我有各种数量的类别,从 10 到 50。为每个类别使用 add_trace 似乎有点棘手。我更喜欢使用 ggplotly 函数。您认为这是一个实际的错误还是只是我以错误的方式使用此功能?
  • 我认为这是一个错误。它经常发生:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2019-06-19
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多