Using the iris dataset from scikit-learn, create a 2×2 grid of subplots. The visualizations are:
Example Output:
Use plt.subplots
for creating a grid of plots and ax
objects to plot specific visualizations.
import matplotlib.pyplot as plt from sklearn.datasets import load_iris import numpy as np def iris_subplots(): iris = load_iris() fig, ax = plt.subplots(2, 2, figsize=(10, 8)) # Top-left: Histogram of sepal length ax[0, 0].hist(iris.data[:, 0], color='blue', bins=20) ax[0, 0].set_title("Histogram of Sepal Length") # Top-right: Scatter plot of sepal width against petal width ax[0, 1].scatter(iris.data[:, 1], iris.data[:, 3], color='green') ax[0, 1].set_title("Scatter plot: Sepal Width vs. Petal Width") # Bottom-left: Box plot of petal lengths by species data_to_plot = [iris.data[iris.target == i][:, 2] for i in range(3)] ax[1, 0].boxplot(data_to_plot) ax[1, 0].set_xticks([1, 2, 3]) ax[1, 0].set_xticklabels(iris.target_names) ax[1, 0].set_title("Boxplot of Petal Lengths by Species") # Bottom-right: Pie chart of species distribution species_counts = np.bincount(iris.target) ax[1, 1].pie(species_counts, labels=iris.target_names, autopct='%1.1f%%') ax[1, 1].set_title("Species Distribution in Iris Dataset") plt.tight_layout() plt.show() # Example usage iris_subplots()
Unlock AI & Data Science treasures. Log in!