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

book
Create a Complete Bar Chart

Tarefa

Swipe to start coding

  1. Assign the second call of the .barh() function to the bar2 variable.

  2. Customize the plot:

    • set x label to 'Rainfall (mm)';
    • y label to 'Month';
    • title to 'Average rainfall level in Indian cities';
    • limit the values on the x-axis to diapason (0, 380).
  3. Add labels to bars:

    • set padding = -5 at the first call;
    • pass bar2 as the first parameter at the second call.

Solução

# 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']
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
bar1 = ax.barh(new_delhi['Month'], new_delhi['Rainfall'], label = 'New Delhi')
bar2 = ax.barh(mumbai['Month'], mumbai['Rainfall'], label = 'Mumbai', left = new_delhi['Rainfall'])

# Set labels, and title
ax.set(xlabel = 'Rainfall (mm)', title = 'Average rainfall level in Indian cities',
ylabel = 'Month', xlim = (0, 380))

# Add labels above bars
ax.bar_label(bar1, padding = -5)
ax.bar_label(bar2, padding = 5)

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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 10
# 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']
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
bar1 = ax.barh(new_delhi['Month'], new_delhi['Rainfall'], label = 'New Delhi')
___ = ax.barh(mumbai['Month'], mumbai['Rainfall'], label = 'Mumbai', left = new_delhi['Rainfall'])

# Set labels, and title
ax.set(xlabel = '___', title = '___',
ylabel = '___', xlim = ___)

# Add labels to bars
___.___(bar1, padding = ___)
ax.bar_label(___, padding = 5)

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