End of Summer - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
12. Step 5 – plot your chart
Check yourself

## Instruction

Now you know everything necessary to plot a bar chart. Let's do this using the R programming language.

To plot a bar chart in R, we will use the ggplot function from the ggplot2 package. Its basic syntax looks like this:

ggplot(data=dataset, aes(x=variable_x, y=variable_y)) + geom_something()

The ggplot() function takes two arguments: data and aes. Then it uses geom_something() to define the chart type. The data argument takes the name of the dataset we want to visualize. The aes() argument sets the variables that will be mapped on the x axis (horizontal) and the y axis (vertical). We define the x variable by writing its name after x=, and the y variable by writing its name after y=.

Let's use the programming we've already done to figure this out. We've put the results we want from the alcohol_consumption dataset in the tab frequency table. We can use that where the dataset name goes. We know that our x axis is based on the pattern variable from tab, and the y axis is based on the n variable. So at this point, we have:

ggplot(data = tab, aes(x = pattern, y = n))

That's only the first part of this command. Next, we need to define the type of chart we're making. If you want to plot a chart with columns (like a bar chart) you will use the geom_col() command. A chart with points (like a scatter plot) would use geom_point(). (Note: We've used geom_something as a placeholder in the code syntax because there are many options available. You can see more chart types at the ggplot2 website.)

The first and second parts of the command are connected with the + sign. We associate this sign with addition, and we are adding elements to the plot with the geom_col() command. In this case, we are adding bars to the graph.

ggplot(data = tab, aes(x = pattern, y = n)) + geom_col()

## Exercise

Use the above explanation to complete the template and plot data from the tab frequency table to a bar graph. Remember to use the + sign and to select the right chart type!

### Stuck? Here's a hint!

You should write:

ggplot(data=tab, aes(x = pattern, y = n)) + geom_col() 