Simple Scatter Plot

Using the iris dataset from scikit-learn, plot a scatter plot of petal length against petal width. Ensure you differentiate each species with a unique color.

Example 1:

Input: Iris dataset petal length and width for species 'setosa'
Output: Scatter plot showcasing petal length vs petal width, differentiated by color for 'setosa'

Use the load_iris method from scikit-learn and Matplotlib’s scatter method for drawing the scatter plot. You might want to use a loop to iterate over the species.

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

def scatter_plot_species():
    iris = load_iris()
    colors = ['red', 'green', 'blue']
    for target, color in zip(range(3), colors):
        subset = iris.data[iris.target == target]
        plt.scatter(subset[:, 2], subset[:, 3], color=color, label=iris.target_names[target])
    plt.xlabel("Petal Length (cm)")
    plt.ylabel("Petal Width (cm)")
    plt.title("Petal Length vs Petal Width by Species")
    plt.legend()
    plt.grid(True)
    plt.show()

# Example usage
scatter_plot_species()

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!