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, andx + width/2
for the second. If we want to build three columns, we can use the following approach:x - width
,x
, andx + width
.
Tâche
Swipe to start coding
- Save data for
'MUMBAI CITY'
in themumbai
variable and all unique values from the'Month'
column in themonths
variable. - Set
width
variable value to0.3
. - Set proper first arguments according to the approach from the theory (displayed above). With the last
.bar()
function call display themumbai
data. Setlabel
to'Mumbai'
. - Set
months
as x ticks labels.
Solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 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 ?
Merci pour vos commentaires !
Section 2. Chapitre 6
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 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
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion