Skip to content

Instantly share code, notes, and snippets.

@betterdatascience
Created October 30, 2020 10:53
Show Gist options
  • Save betterdatascience/12a45c29f28d9f5a262b9bbc5574e470 to your computer and use it in GitHub Desktop.
Save betterdatascience/12a45c29f28d9f5a262b9bbc5574e470 to your computer and use it in GitHub Desktop.
002_powerbi_shiny
library(shiny)
library(gapminder)
library(dplyr)
library(ggplot2)
ui <- fluidPage(
titlePanel("Gapminder explorer", windowTitle = NULL),
sidebarPanel(
width = 3,
tags$h4("Filter"),
selectInput(
inputId = "continentSelect",
label = "Continents",
choices = c("Africa", "Americas", "Asia", "Europe", "Oceania"),
selected = c("Africa", "Americas", "Asia", "Europe", "Oceania"),
multiple = TRUE
)
),
mainPanel(
width = 9,
fluidRow(
column(7, tags$div(
tags$h3("Average life expectancy through time"),
plotOutput("line")
)),
column(5, tags$div(
tags$h3("Total population per continent"),
plotOutput("bar")
))
),
fluidRow(
column(12, tags$div(
tags$h3("Life expectancy vs. GDP per capita"),
plotOutput("scatter")
))
)
)
)
server <- function(input, output) {
output$line <- renderPlot({
dataLifeExp <- gapminder %>%
filter(continent %in% input$continentSelect) %>%
group_by(year, continent) %>%
summarise(avgLifeExp = mean(lifeExp))
ggplot(dataLifeExp, aes(x = year, y = avgLifeExp, color = continent)) +
geom_line(size = 1.5) +
labs(x = "Year", y = "Average life expectancy") +
theme(
plot.margin = unit(c(2, 0, 0, 0), "cm"),
legend.position = c(0.25, 1.05),
legend.direction = "horizontal"
)
})
output$bar <- renderPlot({
popPerContinent <- gapminder %>%
filter(continent %in% input$continentSelect) %>%
mutate(maxYear = max(year)) %>%
filter(year == maxYear) %>%
select(continent, pop) %>%
group_by(continent) %>%
summarise(total = sum(pop))
ggplot(popPerContinent, aes(x = reorder(continent, -total), y = total)) +
geom_bar(stat = "identity", fill = "#519bff") +
labs(x = "Continent", y = "Total population") +
geom_text(aes(label = formattable::comma(total, digits = 0)), vjust = -0.3, size = 5) +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
)
})
output$scatter <- renderPlot({
lifeExpWithGdp <- gapminder %>%
filter(continent %in% input$continentSelect) %>%
select(continent, gdpPercap, lifeExp)
ggplot(lifeExpWithGdp, aes(x = lifeExp, y = gdpPercap, color = continent)) +
geom_point(alpha = 0.7) +
labs(x = "Life expectancy", y = "GDP per capita") +
theme(
plot.margin = unit(c(2, 0, 0, 0), "cm"),
legend.position = c(0.15, 1.05),
legend.direction = "horizontal"
)
})
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment