# Bar Graphs In Python

Hi there. I have been experimenting with creating bar graphs in Python. Here is some stuff that I have come up with.

Sections

A Regular Bar Graph

A Horizontal Bar Graph

Side By Side Bars

References

A Regular Bar Chart

To start off, the numpy and matplotlib packages are loaded into Python.

I have manually created some sample data from a favourite colour survey for a classroom. The colour choices are red, green, blue, black, orange and purple. The counts associated with the colours are 8, 11, 14, 10, 12 and 20. In the code, the np.arange(len(colours)) is used for setting up the x-axis in the plot.

To create the bar graph, the plt.bar() function is used. In the arguments, I have y_position in the x-axis, y in the y-axis, the bar-width as 0.5, centered alignment, lightgreen bars, and a label that says Class #1.

The above code on its own is not enough. Modifications to axes and adding labels is necessary for creating a presentable bar graph plot.

In order to show the plot, use the function plt.show().

A Horizontal Bar Graph

Creating horizontal bar graph plots requires some slight adjustments from the previous code. To get the sideways bar, the plt.barh() function will do the trick. Do keep in mind that the labels have to be adjusted as you have switched values and labels from x to y and vice versa.

I have also adjusted the title font to Comic Sans MS.

Side By Side Bars

This section deals with side by side vertical bars in the bar graph. Having side by side bars is good for comparing different groups and gives the audience a good idea of how each group does depending on various criteria.

In this example, I include a second class and their results on their favourite colours.

In the side by side bar graph, I use a subplots function for double bars. I have the first set of bars from class #1 set up in plt.bar() like in the previous section. For the second of set of bars for class #2, it is important to note that y-position + bar width is used to create the bars beside the first set of bars. These second set of bars are red.

After setting up the two set of bars, the settings for the axes, title, fonts and labels are coded into Python.

References

• Python Data Visualization Cookbook By Igor Milovanović
• https://pythonspot.com/en/matplotlib-bar-chart/
• https://stackoverflow.com/questions/3777861/setting-y-axis-limit-in-matplotlib
• https://stackoverflow.com/questions/21321670/how-to-change-fonts-in-matplotlib-python