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

book
Create a Horizontal Bar Chart

Task

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()

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 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()

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt