I am struggling with the order of bars in ggplot. To keep things simple: here is the code I am using to create the plot:
plot_data <- data() %>%
filter(Name %in% input$polymers)
print(plot_data)
ggplot(data = plot_data, aes(x = ID_Polymer, y = value), position = position_dodge(width = 1)) +
geom_bar(aes_string( fill=razeni()), position = position_dodge(width = 1), stat="identity", color="white")+
theme_minimal() +
theme(legend.text=element_text(size=21))+
theme(text = element_text(size=21))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
ggtitle(input$title_text_box_id) +
labs(x = "", y = input$ylabel_text_box_id) +
geom_text(aes(x = ID_Polymer, y = value,Group=Polymer,label=value),
position = position_dodge(width = 1),vjust=2, size=5,colour = "white", fontface = "bold") +
scale_fill_tableau("Tableau 10")+
scale_x_discrete(labels=c(xpopisky()))#puts a reactive in x labels
fill argument is reactive, that the user chooses in the shiny app.
The results looks like this:
I would like the two blue bars and the two red bars be side by side, like at this post ggplot can not group bars
The tricky thing is, that the fill arguments changes by user input from shiny app and so must change the order of bars.
something like:
aes_string(dodge = razeni())
or aes_string(order = razeni())
I hope the issue is clear and I will be glad for any suggestions on how to deal with it.
So, If anyone struggles with the same issue, here is my solution, that worked for my case:
first I create a reactive data.frame
with the data. Then I make a chosen column of the table a factor ("ID_Polymer" in my case), I set the levels of the factor and I use order()
function with an argument that is selected by the user (which is done by in shinyUI()
by selectInput
input$groupby
). The code goes like this:
dataforplot <- reactive({
plot_data <- data() %>%
filter(Name %in% input$polymers)
plot_data$ID_Polymer <- factor(plot_data$ID_Polymer,
levels =plot_data$ID_Polymer[ order(plot_data[[input$groupby]])])
return(plot_data) # so it returns the data frame and not only the column plot_data$ID_Polymer
})
and than I just create a ggplot:
plotInput <- reactive({
ggplot(data = dataforplot(), aes(x = ID_Polymer, y = value), position = position_dodge(width = 1)) +
})
This solution worked for me so I hope it helps.