Visualize your data
7. Draw the histogram
Work with your chart 2
Check yourself

Instruction

So far, we have learned one ggplot geometry command: geom_col(), which is used for bar charts. Let's learn another that's just for histograms: geom_histogram(). It is used like the bar chart command:

ggplot(data=dataset, aes(x=variable_x)) + geom_histogram()

After the main ggplot function, which specifies the dataset and variable we will use, we simply add a + sign and geom_histogram().

In ggplot, each geometry represents a different chart; therefore, each geom command may work differently or need different data. Because geom_histogram() does all the math for us, we don't have to manually prepare the data. We don't even have to set a variable for the vertical (y) axis; it is always going to be frequencies or proportional values, which are calculated for us. We just set the x argument in aes() to the appropriate variable – in this case, the consumption variable.

Exercise

Use the above syntax to create a histogram for the consumption variable in the alcohol_consumption dataset. Set consumption as the x argument.

When you're done, press the Run and Check Code button to check your code.

Stuck? Here's a hint!

You should write:

ggplot(
  alcohol_consumption, 
  aes(x = consumption)) + geom_histogram()