I have a plot that is a simple barplot of number of each type of an event. I need the labels of the plot to be under the plot as some of the events have very long names and were squashing the plot sideways. I tried to move the labels underneath the plot but it now gets squashed upwards when there are lots of event types. Is there a way of having a static plot size (i.e. for the bar graph) so that long legends don't squash the plot?
My code:
ggplot(counts_df, aes(x = Var2, y = value, fill - Var1)+
geom_bar(stat = "identity") +
theme(legend.position = "bottom") +
theme(legen.direction = "vertical") +
theme(axis.text.x = element_text(angle = -90)
The result:
I think this is because the image size must be static so the plot gets sacrificed for the axis. The same thing happens when I put a legend beneath the plot.
Best Answer
There a several ways to avoid overplotting of labels or squeezing the plot area or to improve readability in general. Which of the proposed solutions is most suitable will depend on the lengths of the labels and the number of bars, and a number of other factors. So, you will probably have to play around.
Dummy data
Unfortunately, the OP hasn't included a reproducible example, so we we have to make up our own data:
"Standard" bar chart
Labels on the x-axis are printed upright, overplotting each other:
Note that the recently added
geom_col()
instead ofgeom_bar(stat="identity")
is being used.OP's approach: rotate labels
Labels on x-axis are rotated by 90° degrees, squeezing the plot area:
Horizontal bar chart
All labels (including the y-axis label) are printed upright, improving readability but still squeezing the plot area (but to a lesser extent as the chart is in landscape format):
Vertical bar chart with labels wrapped
Labels are printed upright, avoiding overplotting, squeezing of plot area is reduced. You may have to play around with the
width
parameter tostringr::str_wrap
.Horizontal bar chart with labels wrapped
My favorite approach: All labels are printed upright, improving readability, squeezing of plot area are is reduced. Again, you may have to play around with the
width
parameter tostringr::str_wrap
to control the number of lines the labels are split into.Addendum: Abbreviate labels using
scale_x_discrete()
For the sake of completeness, it should be mentioned that
ggplot2
is able to abbreviate labels. In this case, I find the result disappointing.