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

book
Create a Stacked Bar Chart

Compito

Swipe to start coding

You are given the same dataframe data. Your tasks are:

  1. Save data for 'MADURAI' in the madurai variable.

  2. Call .bar() function twice:

    • the first time to build bars for the new_delhi data (the 'Month' column on the x-axis and the 'Rainfall' column on the y-axis);
    • the second time to build bars for the madurai data above built ones (the same columns and order as for the new_delhi data).

    Use 'New Delhi' and 'Madurai' as the label parameters.

  3. Display the legend of the plot.

Soluzione

# 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.bar(new_delhi['Month'], new_delhi['Rainfall'], label = 'New Delhi')
ax.bar(madurai['Month'], madurai['Rainfall'], label = 'Madurai', bottom = new_delhi['Rainfall'])

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

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 4
# 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']
___ = data.loc['___']

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

# Initialize the bar chart
ax.bar(new_delhi['Month'], new_delhi['Rainfall'], label = '___')
ax.bar(___['___'], madurai['___'], label = 'Madurai', bottom = ___['Rainfall'])

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