0

I have a pyramid ggplot in shiny where I can change the number of bars with select input. However, when I choose a small number, the width of the bars massively increases to fit the height of the plot. I have tried a couple of methods but I have not been successful.

Here is my current UI for this particular chart;

UI

mainPanel(fluidRow(column(10,plotOutput("exercise3", height =10000)%>% withSpinner(color="#0dc5c1"))),
                                 box(sliderInput("num", "Number of types of exercises",min = 0, max = 300,step=10,value=c(0,300)), width = 12),
                                 width = 10)

Server

exercisestat<- reactive({
test2<-dataset[dataset$n%in% seq(from=min(input$num),to=max(input$num)),]

})

output$exercise3<-renderPlot({ggplot(exercisestat(), mapping=aes(x = exercisetype, y = COST, fill = `different costs`)) +
  geom_bar(exercisestat() %>% filter(`Cost Type` == "Fixed Costs"),
           stat = "identity",
           position = "stack",
           width=1,
           mapping=aes(reorder(exercisetype, COST), y=COST)) +
  geom_bar(exercisestat() %>% filter(`Cost Type` == "Variable Costs"),
           stat = "identity",
           position = "stack",
           width=1,
           mapping = aes(y = -COST))+
  coord_flip()+
  geom_hline(yintercept=0) +
  theme_economist(horizontal = TRUE) + scale_y_continuous(position = "right", labels =scales::dollar_format(scale = .001, suffix = "K"))+
  scale_fill_economist() +
  labs(fill = "", x = "", y = "")
},height = function() {200 + (length(exercisestat()))})

I have essentially followed the same procedure as Population pyramid w projection in R

I want the width of the bars to stay the same width no matter how small or large the sample I select (by changing the number of types of exercises), I want the height to increase or decrease depending on what number I have selected.

As above, I have tried the above; height = function() {200 + (length(exercisestat()))}) but it doesn't work, I would really appreciate any help.

newbie
  • 21
  • 5

1 Answers1

0

Without being able to reproduce your problem, try

geom_bar(position = position_dodge2(width = 0.5, preserve = "single"))

instead of

position = "stack"

You can use your desired value for width.

memokerobi
  • 143
  • 10
  • thank you, it works but it unstacks my chart. I would like it stacked, do you know away where I can do this and keep it stacked? thank you – newbie Mar 15 '21 at 01:47
  • Try to see if you can find anything you can use here https://stackoverflow.com/questions/12715635/ggplot2-bar-plot-with-both-stack-and-dodge – memokerobi Mar 15 '21 at 18:20