'How to prevent a plot cut off

I would like to extend the (right) margin of my plot:

Cluster

I tried it with par(omi=c(10,10,5,20)) (arbitrary values) but it doesn't work.

par(oma=c(10,10,5,20))
ggplot(df, aes(Cluster, Number_of_observations)) + 
  geom_bar(position = 'dodge', stat='identity', colour="Darkblue", fill = "skyblue") +
  geom_text(aes(label=Number_of_observations), position=position_dodge(width=0.9), 
            hjust = -0.25, vjust=-0.25) +
  coord_flip() +
  theme_bw()


Solution 1:[1]

Posting my comment as an answer, as requested, & expanding on it to justify it being an answer :)

As @RichardTelford noted, par works with the base plotting commands, as it sets parameters for the graphical device. Each subsequent plot-related command makes some change on the device. For example, points draws points at the specified coordinates, text adds text strings, etc. Things are done sequentially. An earlier command (such as par) affects a later command, but not vice versa.

ggplot2 works differently. The ggplot(...) + geom_XXX(...) + scale_XXX(...) + theme(...) commands create a ggplot object. Except for ggplot(...), which initializes the object & must come first, the order for other parts can be switched around with no real impact to the result (though maintaining some order would make your code easier to read). This means that to affect the appearance for any part of a plot created through ggplot2, you have to make the change within its commands, not outside using par.

In your case, the following would work:

ggplot(df, aes(Cluster, Number_of_observations)) + 
  geom_col(position = 'dodge', colour = "Darkblue", fill = "skyblue") +
  geom_text(aes(label = Number_of_observations), position = position_dodge(width = 0.9), 
            hjust = -0.25, vjust = -0.25) + 
  expand_limits(y = 900000) + # or some other arbitrarily large number
  coord_flip() +
  theme_bw()

I also recommend using geom_col(...) instead of geom_bar(stat = "identity", ...). They are equivalent, but the former requires less typing.

Solution 2:[2]

I solved this issue with expand_limits. See; https://ggplot2.tidyverse.org/reference/expand_limits.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Z.Lin
Solution 2 joshng