绘图分组的条形图不显示负值

plotly grouped bar chart does not show negative values

背景: 我正在更新一个小型 Shiny 应用程序以使用 plotly 而不是 ggplot2 以使图表具有交互性。 (注意:我对 R 比较陌生)。

问题: 我使用的是分组条形图,有时会混合使用正值和负值。使用 ggplot2 和 renderPlot 时,我的图表按预期工作。但是,当使用 plotly 和 renderPlotly 时,图表上的条形图都显示为正。当我将鼠标悬停在条形图上时,我可以看到负值。

示例代码:

dat1 <- data.frame(
  Item = factor(c("Female","Female","Male","Male")),
  Attributes = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
  Score = c(13.53, 16.81, -16.24, 17.42)
)

build_chart <- function(df){

  p <- ggplot(df, aes(factor(Attributes), Score, fill=Item)) +
    geom_bar(stat="identity", position="dodge") +
    coord_flip()

  p
}

build_chart(dat1)
ggplotly(build_chart(dat1))

插图:

想要的结果(ggplot2):

绘图结果:

我看到很多情况下 ggplotly() 给出了意想不到的结果。这是一个不完美的情节界面,有时运行良好,但经常出现故障。您可以很容易地直接在 plotly 中构建图形。直接使用 plotly API 而不是通过 ggplot 也有一个优点,它可以让您访问许多无法使用 ggplot

控制的图表属性
plot_ly(dat1, type = "bar", x=Score, y=Attributes, group=Item, orientation="h") 

好像今天有点变化:

dat1 <- data.frame(
Item = factor(c("Female","Female","Male","Male")),
属性 = factor(c("Lunch","Dinner","Lunch","Dinner"),
levels=c("Lunch","Dinner")),
分数 = c(13.53, 16.81, -16.24, 17.42) )

图书馆(剧情)

之前: plot_ly(dat1, type = "bar", x=Score, y=Attributes, group=Item, orientation="h")

现在它对我有用:
plot_ly(type = "bar", x=dat1$Score, y=dat1$Attributes, split=dat1$Item, orientation="h")