A bar plot represents the relationship between a measurement variable and a categorical variable. In most cases, each of the bars will display the mean of a specific group, which will allow for visualizing the difference between groups in an experiment.

There are two variants of the bar plot: horizontal and vertical. One would prefer to use a horizontal bar plot when the categorical variable is nominal (labels/names), while the vertical plot is preferred when the categorical variable is ordinal (numbers, series, dates). Here, we will see how to make a horizontal bar plot.

In the following example, we will use ggplot() to draw a bar plot that shows the total precipitations registered in 2018 at two locations (Lygra, Hordaland and Østerbø, Sogn og Fjordane). Here are the variables and dataframe:

# variable 1
location <- c("Lygra", "Østerbø")
# variable 2
precipitations <- c(1229.8, 515.9)
# dataframe
df <- data.frame(location, precipitations)



We start by drawing a regular, vertical bar plot. We may use either geom_col() or geom_bar() to create the plot with ggplot(), as previously discussed here. Here we use geom_col():

ggplot(df, aes(location, precipitations)) +     
  geom_col()



To obtain a horizontal bar plot, we will add the function coord_flip(). This function flips the whole plot so that the X-axis becomes the Y-axis and vice versa:

ggplot(df, aes(location, precipitations)) +      
  geom_col() +
  coord_flip()                  



You may bring colors to the bars using color= and fill=:

ggplot(df, aes(location, precipitations)) +     
  geom_col(color = "blue", fill = "white", width = .5) +
  coord_flip()       



Finally you may adjust the width of the bars with the argument width=:

ggplot(df, aes(location, precipitations)) +     
  geom_col(width = .25) +
  coord_flip()       



Adding plot title, axis titles, ticks, labels and other essential elements

In this section, you will learn how to set/modify all the necessary elements that make a plot complete and comprehensible. Such elements are: