Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Create a Grouped Bar Chart | Bar Charts
Visualization in Python with matplotlib

book
Create a Grouped Bar Chart

Note

To build 2 columns, we need to set x - width/2 as the first parameter with the first .bar() call, and x + width/2 for the second. If we want to build three columns, we can use the following approach: x - width, x, and x + width.

Tâche

Swipe to start coding

  1. Save data for 'MUMBAI CITY' in the mumbai variable and all unique values from the 'Month' column in the months variable.
  2. Set width variable value to 0.3.
  3. Set proper first arguments according to the approach from the theory (displayed above). With the last .bar() function call display the mumbai data. Set label to 'Mumbai'.
  4. Set months as x ticks labels.

Solution

# Import the libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Load the data
data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/ed80401e-2684-4bc4-a077-99d13a386ac7/rainfall+in+india.csv', index_col = 0)

# Filter to certain cities
new_delhi = data.loc['NEW DELHI']
madurai = data.loc['MADURAI']
mumbai = data.loc['MUMBAI CITY']
months = data['Month'].unique()

# Create numpy array and width
x = np.arange(len(months))
width = 0.3

# Create Axes and Figure objects
fig, ax = plt.subplots()

# Initialize the bar chart
ax.bar(x - width, new_delhi['Rainfall'], width, label = 'New Delhi')
ax.bar(x, madurai['Rainfall'], width, label = 'Madurai')
ax.bar(x + width, mumbai['Rainfall'], width, label = 'Mumbai')

# Set x ticks
plt.xticks(x, months)

# Display the legend and the plot
plt.legend()
plt.show()

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 6
single

single

# Import the libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Load the data
data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/ed80401e-2684-4bc4-a077-99d13a386ac7/rainfall+in+india.csv', index_col = 0)

# Filter to certain cities
new_delhi = data.loc['NEW DELHI']
madurai = data.loc['MADURAI']
mumbai = data.loc['___']
months = data['___'].unique()

# Create numpy array and width
x = np.arange(len(months))
width = ___

# Create Axes and Figure objects
fig, ax = plt.subplots()

# Initialize the bar chart
ax.bar(x - ___, new_delhi['Rainfall'], width, label = 'New Delhi')
ax.bar(x, madurai['Rainfall'], width, label = 'Madurai')
ax.bar(x + width, ___['___'], width, label = '___')

# Set x ticks
plt.xticks(x, ___)

# Display the legend and the plot
plt.legend()
plt.show()

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

some-alt