Bar graphs

Bar graphs are useful for comparing quantities in different categories. They can be arranged either horizontally or vertically to present the mean estimate and error bands. They can be used to present various statistics of your predictors and how they relate to the target variable.

In our example, we will present the mean and standard deviation for the four variables of the Iris dataset:

In: from sklearn.datasets import load_iris 
import numpy as np
import matplotlib.pyplot as plt
iris = load_iris()
average = np.mean(iris.data, axis=0)
std = np.std(iris.data, axis=0)
range_ = range(np.shape(iris.data)[1])

In our representation, we will prepare two subplots: one with horizontal bars (plt.barh), and the other with vertical bars (plt.bar). The standard error is represented by an error bar, and according to the graph orientation, we can use the xerr parameter for horizontal bars and yerr for vertical ones:

In: plt.subplot(1,2,1) # defines 1 row, 2 columns panel, activates figure 1
plt.title('Horizontal bars')
plt.barh(range_,average, color="r",
xerr=std, alpha=0.4, align="center")
plt.yticks(range_, iris.feature_names)
plt.subplot(1,2,2) # defines 1 row 2 column panel, activates figure 2
plt.title('Vertical bars')
plt.bar(range_,average, color="b", yerr=std, alpha=0.4, align="center")
plt.xticks(range_, range_)
plt.show()

Horizontal and verticals bars are now together in the same plot:

It is important to note the use of the plt.xticks command (and of plt.yticks for the ordinate axis). The first parameter informs the command about the number of ticks that have to be placed on the axis, and the second one explicates the labels that have to be put on the ticks.

Another interesting parameter to notice is alpha, which has been used to set the transparency level of the bar. The alpha parameter is a float number ranging from 0.0, fully transparent, to 1.0, which causes the color to be shown in different levels of opaqueness.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset