Using ggplot, I could create a population pyramid within Shiny framework which works perfectly. I tried to make it fancier using ggplotly, but could not get proper results. Here are the successful codes.
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()
})
Here are the failed codes.I changed the above codes slightly trying to invlove ggplotly. I get the error of "'bar' objects don't have these attributes: 'mode'". I expect a population pyramid that interactively shows the percentage and correspoding gender on the bars.
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()
})