首页 > 解决方案 > ggplotly 不提供交互式人口金字塔

问题描述

使用 ggplot,我可以在 Shiny 框架内创建一个完美运行的人口金字塔。我尝试使用 ggplotly 让它更漂亮,但无法获得正确的结果。这是成功的代码。

pyramidPlot <- reactive ({
ggplot (pyramid(), aes(x = Age_Group, y = Percentage, fill = Sex, 
 label=Percentage)) +
  geom_bar(subset = .(Sex == "Females"), stat = "identity") +
  geom_bar(subset = .(Sex == "Males"), stat = "identity") + 
  coord_flip() +
  labs(
    x = "Age Groups",
    y = "Population Size (%)",
    caption = (""),
    face = "bold.italic"
  ) +
  scale_fill_brewer(palette = "Set1") +
  theme_bw() +
  scale_y_continuous(labels=abs_comma <- function (x, ...) {
    format(abs(x), ..., big.mark = ",", scientific = FALSE, trim = 
 TRUE)
  })+
  theme(plot.title = element_text(
    hjust = 0.5,
    size = 15,
    colour = "Black",
    face = "bold.italic"
  ),axis.text=(blue.bold.italic.10.text), 
    axis.title=blue.bold.italic.14.text)+
  ggtitle(paste(
    "Population Pyramid for",
    input$county,
    "in",
    input$years
  ))
  })
 output$pyramid <- renderPlot ({
  pyramidPlot()
   })

这是失败的代码。我稍微改变了上面的代码,试图让ggplotly参与进来。我收到“'bar'对象没有这些属性:'mode'”的错误。我希望有一个人口金字塔,它可以交互地显示条形上的百分比和相应的性别。

pyramidPlot <- reactive ({
g<- ggplot(pyramid(), aes(x = Age_Group, y = Percentage, fill = Sex, 
 label=Percentage)) +
  geom_bar(subset = .(Sex == "Females"), stat = "identity") +
  geom_bar(subset = .(Sex == "Males"), stat = "identity") + 
  coord_flip() +
  labs(
    x = "Age Groups",
    y = "Population Size (%)",
    caption = (""),
    face = "bold.italic"
  ) +
  #  geom_text(aes(y = Percentage + 1 * sign(Percentage), label = 
  Percentage2), 
        #    position = position_dodge(width = 0), hjust=0,vjust=0 
  ,size =5, colour = "Black",
          #  face = "bold.italic"
           # )+

  scale_fill_brewer(palette = "Set1") +
  theme_bw() +
  scale_y_continuous(labels=abs_comma <- function (x, ...) {
    format(abs(x), ..., big.mark = ",", scientific = FALSE, trim = 
   TRUE)
  })+
 # annotate("text", x = 4.3, y = -100, label = "Women", fontfacet = 
  "bold") + 
 # annotate("text", x = 4.3, y = -200, label = "Men", fontfacet = 
   "bold") +
  theme(plot.title = element_text(
    hjust = 0.5,
    size = 15,
    colour = "Black",
    face = "bold.italic"
  ),axis.text=(blue.bold.italic.10.text), 
  axis.title=blue.bold.italic.14.text)+
  ggtitle(paste(
    "Population Pyramid for",
    input$county,
    "in",
    input$years
  ))
   ggplotly(g)
   })
   output$pyramid <- renderPlot ({
    pyramidPlot()
   })

标签: rggplot2shinyplotlyggplotly

解决方案


推荐阅读