5

I'm using the likert package by jbryer and want to visualise the data with stacked bar plots. The size/width of these bar plots depends on how many bars are in the graph, i.e. with only one bar the bar is pretty wide, while they get thinner the more bars are plotted.

I'd like to costumly set the size/width of the bar, so that they stay the same, no matter how many bars are plotted in the graph, i.e. that the bar size is the same for the plots of l29_5 and l29_2.

Likert bar plot with two bars

Likert bar plot with five bars

library(ggplot)
library(likert)    
data(pisaitems)

items29_5 <- pisaitems[,substr(names(pisaitems), 1,5) == 'ST25Q']
colnames(items29_5) <- c("Magazines", "Comic books", "Fiction", 
                    "Non-fiction books", "Newspapers")

items29_2 <-  items29_5 %>% 
  select("Magazines", "Comic books")


l29_5 <- likert(items29_5)
l29_2 <- likert(items29_2)

plot(l29_5)
plot(l29_2)
camille
  • 16,432
  • 18
  • 38
  • 60
Torakoro
  • 162
  • 7
  • 3
    The `plot.likert` function can have no control over this, it's a matter of the canvas size within the controlling environment. If you're rendering this in an r-markdown document, you can set the `fig.height` for a code chunk `programmatically` based on how many questions you have in that plot. It should be relatively linear, i.e., `mx+b`, where `b` is the constant height due to x-axis and legend, and `m` is a per-likert height. – r2evans Feb 14 '20 at 18:40

1 Answers1

4

The function likert.bar.plot(..) doesn't have any parameters for the width of the bins. However, it returns an object of class ggplot, so that it can be processed with standard ggplot2 instructions.
The final plot consists of several ggplot layers. The problem here is not to add a new instruction or layer to the plot, but rather to update parameters for one or more inner layers. Namely, we need to set the width for all the layers containing geom_bar(). For this, we find the relevant layers at first:

p <- likert.bar.plot(l29_2)
p$layers

From the output, it can be seen that geom_bar is included in layers 2 and 3. Then we can modify them by adding the width parameter:

p$layers[[2]]$geom_params$width = 0.3
p$layers[[3]]$geom_params$width = 0.3
p

likert plot with predefied bin widths

DzimitryM
  • 561
  • 1
  • 5
  • 13
  • Thanks! Do you know how the distance between the items (bars) can be reduced? – kaiya Oct 07 '20 at 16:20
  • 1
    @kaiya, the distance between the bars is calculated automatically depending on the proportions of the viewport. As a workaround, I'd suggest to manually adjust the aspect ratio at zooming or exporting the image in order to get the required distance. – DzimitryM Oct 08 '20 at 17:33