I am trying to make a percentage percent bar chart in R with two reactive values. Below is the code that I am using. I keep getting the error "object 'race' not found" and "object 'gender' not found". However, both "race" and "gender" are in the dataframe "filtered_data()". Do you know how I can fix this?
Here is the tab panel:
tabPanel(title = "Comparison Bar Plot",
h1("Bar Chart"),
h3("Adjust"),
selectInput(inputId = "AxisX", label = "X Axis Variable",
choices = c("Race", "Gender"),
selected = "Race"),
selectInput(inputId = "AxisY", label = "Y Axis Variable",
choices = c("Race", "Gender"),
selected = "Gender"),
plotlyOutput("comparisonbarplot")
)
And here is the output:
output$comparisonbarplot <- renderPlotly({
filtered_data() %>% group_by(switch(input$AxisX, Race=race,Gender=gender), switch(input$AxisY, Race=race,Gender=gender)) %>%
summarise(count=n()) %>%
mutate(perc = count/sum(count)) %>%
ggplot(aes(x = switch(input$AxisX, Race=race,Gender=gender), y = perc*100, fill=switch(input$AxisY, Race=race,Gender=gender))) +
scale_fill_manual(values =cbPalette) +
geom_bar( stat="identity") +
xlab("Race/Ethnicity") +
ylab("Percent") +
labs(title = "Race/Ethnicity and Gender of Defendants \n in Dutchess County Courts Starting Fall 2018", fill = "Gender:")+
theme_economist() +
theme(plot.title = element_text(hjust = 0.5))
})
We can return a string in switch
and then use group_by
with across
output$comparisonbarplot <- renderPlotly({
fstgrp <- switch(input$AxisX,
Race="race",
Gender="gender")
scndgrp <- switch(input$AxisY,
Race="race",
Gender="gender")
filtered_data() %>%
group_by(across(all_of(c(fstgrp, scndgrp)))) %>%
summarise(count=n()) %>%
mutate(perc = count/sum(count)) %>%
ggplot(aes(x = .data[[fstgrp]], y = perc*100,
fill=.data[[scndgrp]])) +
scale_fill_manual(values =cbPalette) +
geom_bar( stat="identity") +
xlab("Race/Ethnicity") +
ylab("Percent") +
labs(title = "Race/Ethnicity and Gender of Defendants \n in Dutchess County Courts Starting Fall 2018", fill = "Gender:")+
theme_economist() +
theme(plot.title = element_text(hjust = 0.5))
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.