Chalarangelo/30-seconds-of-code

New snippet ideas

caeltarifa opened this issue · 1 comments

Discussed in https://github.com/30-seconds/30-seconds-of-code/discussions/1925

Scatter plot on linear regression, less code and effort

Originally posted by **cael** May 30, 2023 This snippet would show how to plot a linear regression in few lines by Seaborn over Matplotlib. By the example, it illustrates the difference between both libraries doing the same, highlighting the simpleness of Seaborn for scatter plots. Seaborn's higher-level function and integration with underlying Matplotlib functionality provides a direct function of linear regression. Without using third-party libraries to perform the calculation, Seaborn makes it more convenient for creating advanced statistical plots with less code and effort.

The dataset illustrated on the plot below shows the comparative that belongs to Seaborn and Matplotlib, respectively.

# Create a scatter plot with regression lines calculated using Seaborn
sns.lmplot(x="sepal_length", y="sepal_width", hue="species", data=iris)
plt.show()

image

# Create a scatter plot using Matplotlib
plt.scatter(iris["sepal_length"], iris["sepal_width"], c=iris["species"].cat.codes)
plt.xlabel('sepal_length')
plt.ylabel('sepal_width')

# Calculate and plot regression lines for each category
for species, group in iris.groupby("species"):
    x = group["sepal_length"]
    y = group["sepal_width"]
    m, b = np.polyfit(x, y, 1)
    plt.plot(x, m * x + b, label=species)

image

Please post these as part of #1925.