ggplotly不提供交互式人口金字塔

时间:2018-12-21 13:03:21

标签: r ggplot2 shiny plotly 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()
   })

0 个答案:

没有答案