首页 文章

图表分组条形图不显示负值

提问于
浏览
4

Background: 我'm working on updating a small Shiny application to use plotly instead ggplot2 in order to make the chart interactive. (Note: I'对R来说相对较新 .

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

Sample code:

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))

Illustration:

Desired result (ggplot2):

ggplot2

plotly result:

plotly

1 回答

  • 5

    我看到很多场合ggplotly()给出意想不到的结果 . 它是一个不完美的界面,有时候效果很好,但经常出现故障 . 您可以非常轻松地直接在图中构建图形 . 直接使用plotly API,而不是通过ggplot也有一个优点,它可以让你访问ggplot无法控制的许多图表属性

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

    enter image description here

相关问题