Using the iris dataset from scikit-learn, plot a bar chart representing the average sepal length of each species. Ensure the bars are colored differently for each species.
Example 1:
Input: Iris dataset average sepal length Output: Bar chart showcasing the average sepal length of each species.
Example 2:
Input: Iris dataset average sepal width Output: Bar chart showcasing the average sepal width of each species.
Use the load_iris method from scikit-learn and Matplotlib’s bar method for drawing the bar chart. Calculate average using numpy’s mean function.
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import numpy as np
def bar_chart_avg_measurement(index, label):
iris = load_iris()
avg_values = [np.mean(iris.data[iris.target == i][:, index]) for i in range(3)]
species = iris.target_names
colors = ['red', 'green', 'blue']
plt.bar(species, avg_values, color=colors)
plt.xlabel("Species")
plt.ylabel(label)
plt.title(f"Average {label} by Species")
plt.grid(axis='y')
plt.show()
# Example usages
bar_chart_avg_measurement(0, "Sepal Length (cm)") # sepal length
bar_chart_avg_measurement(1, "Sepal Width (cm)") # sepal width
Unlock AI & Data Science treasures. Log in!