Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jrosell/54e518a3bc58386597a68a9b272a054f to your computer and use it in GitHub Desktop.

Select an option

Save jrosell/54e518a3bc58386597a68a9b272a054f to your computer and use it in GitHub Desktop.

ggplot2 (R)

library(ggplot2)

ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
  geom_point() +
  geom_smooth(se = FALSE)

matplotlib (Python)

import matplotlib.pyplot as plt
import numpy as np
from seaborn import load_dataset

mpg = load_dataset("mpg")

classes = mpg["class"].unique()
colors = plt.cm.tab10.colors

plt.figure(figsize=(8,6))

for i, cls in enumerate(classes):
    subset = mpg[mpg["class"] == cls]
    plt.scatter(subset["displ"], subset["hwy"], color=colors[i], label=cls)

    # regression line (numpy polyfit for each group)
    z = np.polyfit(subset["displ"], subset["hwy"], 1)
    p = np.poly1d(z)
    plt.plot(subset["displ"], p(subset["displ"]), color=colors[i])

plt.xlabel("Displacement")
plt.ylabel("Highway MPG")
plt.legend(title="Class")
plt.show()

plotnine (Python)

from plotnine import ggplot, aes, geom_point
from plotnine.data import mpg
(
    ggplot(mpg, aes(x="displ", y="hwy", color="class"))
    + geom_point()
    + geom_smooth(se=False)
)

altair (Python)

import altair as alt
from vega_datasets import data

mpg = data.cars()

points = alt.Chart(mpg).mark_point().encode(
    x="Displacement",
    y="Miles_per_Gallon",
    color="Origin"
)

smooth = alt.Chart(mpg).transform_regression(
    "Displacement", "Miles_per_Gallon"
).mark_line()

points + smooth

seaborn objects (Python)

import seaborn.objects as so
from seaborn import load_dataset
mpg = load_dataset("mpg")
(
    so.Plot(mpg, x="displ", y="hwy", color="class")
    .add(so.Dot())
    .add(so.Line(), so.PolyFit()) 
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment