I am trying to build a shiny app with the worldphones dataset but the ggplot barchart is not showing.
I am using two separate files, i.e ui.R and server.R
Below you can find my code. Could you please help me with it?
library(datasets)
library(tidyverse)
library(shiny)
# Use a fluid Bootstrap layout
fluidPage(
# Give the page a title
titlePanel("Telephones by country"),
# Generate a row with a sidebar
sidebarLayout(
# Define the sidebar with one input
sidebarPanel(
selectInput("Country", "Country:",
choices=colnames(WorldPhones)),
),
# Create a spot for the barplot
mainPanel(
plotOutput("phonePlot")
)
)
)
library(datasets)
library(tidyverse)
library(shiny)
library(ggplot2)
# Define a server for the Shiny app
function(input, output) {
# Fill in the spot we created for a plot
output$phonePlot <- renderPlot({
# Render a barplot
WorldPhones %>%
as.data.frame() %>%
rownames_to_column("Year") %>%
pivot_longer(cols = -Year, names_to = "Country", values_to = "Users") %>%
ggplot(aes(x = Year, y = input$Users)) +
geom_col() +
theme_minimal()
})
}
The aes() call in ggplot() references input$Users, but input$Users
doesn't exist. Instead, you should filter the dataset based on the selected input$Country
which does exist and use it to plot Users.
library(datasets)
library(tidyverse)
library(shiny)
library(ggplot2)
# Use a fluid Bootstrap layout
ui <- fluidPage(
# Give the page a title
titlePanel("Telephones by Country"),
# Generate a row with a sidebar
sidebarLayout(
# Define the sidebar with one input
sidebarPanel(
selectInput("Country", "Country:", choices = colnames(WorldPhones)),
),
# Create a spot for the barplot
mainPanel(plotOutput("phonePlot"))
)
)
# Define a server for the Shiny app
server <- function(input, output) {
# Fill in the spot we created for a plot
output$phonePlot <- renderPlot({
# Render a barplot
WorldPhones %>%
as.data.frame() %>%
rownames_to_column("Year") %>%
pivot_longer(cols = -Year, names_to = "Country", values_to = "Users") %>%
filter(Country == input$Country) %>% # Filter for selected country
ggplot(aes(x = Year, y = Users)) + # Use Users as the y value
geom_col(fill = "steelblue") +
labs(
title = paste("Telephones in", input$Country),
x = "Year",
y = "Number of Telephones"
) +
theme_minimal()
})
}
# Run the Shiny app
shinyApp(ui, server)