Axes, Legend & Title

Axes

Often, the axes need to be adjusted to better represent the data. If you have been experimenting and trying to display values above the bars, you may have noticed that not all values from each bar were displayed. This happened because the y-axis was too short. You can easily limit the axes in the scale_x_continuous() function. continuous is used here because it deals with the data type (integer or numeric). To limit the axes, you use the argument limits = c(...) and specify the minimum and maximum values.

barplotBeyonce <- barplotBeyonce +
  geom_text(
    stat = "count", 
    aes(label = ..count..), 
    vjust = -2.5, 
    size = 8,
    color = "white"
  ) +
  scale_y_continuous(
    limits = c(
      0, 
      1750
    )
  )

barplotBeyonce
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(count)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

Similarly, you can determine the axis markings in the scale_y_continuous function. You do this in the breaks argument by simply specifying a sequence.

barplotBeyonce <- barplotBeyonce + 
  scale_y_continuous(
    breaks = seq(
      0, 
      1750, 
      100
    ),
    limits = c(
      0,
      1750
    )
  )

barplotBeyonce

The same goes for the x-axis: You know that the variable edu is a factor with five levels (plus NA). So, it is not a continuous variable. Therefore, you use the function scale_x_discrete() here.

barplotBeyonce <- barplotBeyonce + 
  scale_x_discrete(
    limits = c(
      "ES-ISCED I", 
      "ES-ISCED II",
      "ES-ISCED III",
      "ES-ISCED IV",
      "ES-ISCED V", 
      NA
    )
  ) 

barplotBeyonce

So, for non-continuous variables, you need to display the categories that should be shown.

Think about or try how you can exclude the <code>NA</code> category?
You want to change the order from the highest to the lowest category. How can you do that?

Legend

Currently, the legend appears on the right. You can change it as you like using the legend.position argument within the additional theme() function:

barplotBeyonce +
  theme(legend.position = "bottom") # left, right, top, or none

You can also customize the legend labels:

barplotBeyonce + 
  scale_fill_manual(
    name = "Bildungsniveau",
    labels = c(
      "sehr niedrig", 
      "niedrig",
      "mittel",
      "hoch",
      "sehr hoch", 
      "NA"
    ),
    values = beyonce_palette(25)
  )

Titles

Now, we just need customized axis labels and titles!

barplotBeyonce + 
  labs(
    x = "Bildungsniveau", 
    y = "Häufigkeiten",
    title = "My first try with ggplot2"
  )

Everything clear? Keep going!