You have to think about tables a bit different. Put your values into individual rows with identifier columns rather then the values from different identifiers into columns.
You can transform your dataframe with something like this:
library(tidyverse)
df <- data.frame(cbind(year, dem_ev, rep_ev)) %>%
rename(Democrat = dem_ev, Republican = rep_ev) %>%
pivot_longer(!year, names_to = "party", values_to = "votes")
It is helpful to test data preparation and plotting in Markdown files rather than directly in shiny.
Then the full example
library(shiny)
library(shinydashboard)
library(ggplot2)
library(plotly)
library(tidyverse)
year <- c(1960,1964,1968,1972,1976,1980,1984,1988,1992,1996,2000,2004,2008,2012,2016,2020)
dem_ev <- c(303,486,191,17,297,49,13,111,370,379,266,251,365,332,227,306)
rep_ev <- c(219,52,301,520,240,489,525,426,168,159,271,286,173,206,304,232)
df <- data.frame(cbind(year, dem_ev, rep_ev)) %>%
rename(Democrat = dem_ev, Republican = rep_ev) %>%
pivot_longer(!year, names_to = "party", values_to = "votes")
# set factors
df$party <- factor(df$party, levels = c("Democrat", "Republican"))
# Define UI for application
ui <- fluidPage(
dashboardPage(
dashboardHeader(title=""),
dashboardSidebar(
sidebarMenu(
menuItem(
"National Results",
tabName = "nat_results",
icon = icon("flag-usa")
)
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "nat_results",
fluidRow(
sliderInput(
"year_select",
"Choose an election year:",
min = 1960, max = 2020, step = 4 ,value = 2020
)
),
fluidRow(
align = 'center',
plotlyOutput("elec_votes_bar")
)
)
)
)
)
)
# Define server logic
server <- function(input, output) {
filtered_data <- reactive({
df %>% filter(year == input$year_select)
})
output$elec_votes_bar <-renderPlotly({
p1 <- ggplot(
data = filtered_data(),
aes(x = party, y = votes, fill = party)) +
scale_fill_manual(values = c("#999999", "#E69F00")) +
geom_bar(stat = "identity") +
coord_flip() +
theme(legend.position = "none") +
ylab('Electoral Votes') +
xlab('') +
ylim(0, max(df$votes))
p1
})
}
# Run the application
shinyApp(ui = ui, server = server)