我正在尝试使用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的值,B型是4,而它应该是2.
你知道如何解决这个问题吗?
答案 0 :(得分:0)
当您打印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)