Contenido del Curso
Visualization in Python with matplotlib
Visualization in Python with matplotlib
Grouped Bars
Instead of placing each new bar above the previous one, there is one more approach to visualize such data: placing bars on the sides of other bars. We call such bar charts grouped bar charts.
The approach of building grouped bars is similar, but with some nuances. First, we need to predefine column widths. Then, we need to generate a sequence of 'positions' (preferably by using np.arange()
). Then, with every call of the .bar()
function we pass the newly created sequence as the first argument, and the values as the second. The third positional argument should be the column width. Then, for better readability, we should set the label
parameter.
Note
To build 2 columns, we need to set
x - width/2
as the first parameter with the first.bar()
call, andx + width/2
for the second. If we want to build three columns, we can use the following approach:x - width
,x
, andx + width
.
# Import library import matplotlib.pyplot as plt import numpy as np # Create data for chart countries = ['United States', 'India', 'Brazil'] agricultural = [333600, 1458996, 214368] industrial = [3722590, 2179020, 672336] services = [15592000, 5826510, 2361296] x = np.arange(len(countries)) width = 0.3 # column width # Create Axes and Figure objects fig, ax = plt.subplots() # Initialize bar chart ax.bar(x - 0.3, agricultural, width, label = 'Agricultural') ax.bar(x, industrial, width, label = 'Industrial') ax.bar(x + 0.3, services, width, label = 'Services') # Set custom ticks plt.xticks(x, countries) # Display the plot plt.legend() plt.show()
We may see, that there we created a numpy
array length of the same as countries, and then used approach from the note above. Also, we used the plt.xticks
function to display countries on the x-axis ticks.
¡Gracias por tus comentarios!