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

book
Create a Horizontal Bar Chart

Tâche

Swipe to start coding

For the same dataframe data build a horizontal bar chart representing the average monthly rainfall level for New Delhi and Madurai. Follow the next steps:

  1. Initialize horizontal bar chart for the new_delhi data. Use values of the 'Month' column as the first parameter and values of the 'Rainfall' column as the second one.
  2. Initialize horizontal bar chart for the madurai data and place it to the right of previously built data (new_delhi). Set label parameter to 'Madurai'.

Solution

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

# 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']

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

# Initialize the bar chart
ax.barh(new_delhi['Month'], new_delhi['Rainfall'], label = 'New Delhi')
ax.barh(madurai['Month'], madurai['Rainfall'], label = 'Madurai', left = new_delhi['Rainfall'])

# 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 8
# Import the libraries
import pandas as pd
import matplotlib.pyplot as plt

# 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']

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

# Initialize the bar chart
___(new_delhi['Month'], new_delhi['___'], label = 'New Delhi')
___(madurai['Month'], madurai['Rainfall'], label = '___', ___ = ___['Rainfall'])

# Display the legend and the plot
plt.legend()
plt.show()
toggle bottom row
some-alt