Skip to content

Instantly share code, notes, and snippets.

@muhammadanas0716
Created January 19, 2023 10:12
Show Gist options
  • Save muhammadanas0716/bee4ec7d5d8cd988515cc519a98eb3d4 to your computer and use it in GitHub Desktop.
Save muhammadanas0716/bee4ec7d5d8cd988515cc519a98eb3d4 to your computer and use it in GitHub Desktop.
Marginal boxplot helps to pinpoint the median, 25th, and 75th percentiles of the X and the Y.
# Import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Import Data
df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")
# Create Fig and gridspec
fig = plt.figure(figsize=(16, 10), dpi= 80)
grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)
# Define the axes
ax_main = fig.add_subplot(grid[:-1, :-1])
ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])
ax_bottom = fig.add_subplot(grid[-1, 0:-1], xticklabels=[], yticklabels=[])
# Scatterplot on main ax
ax_main.scatter('displ', 'hwy', s=df.cty*5, c=df.manufacturer.astype('category').cat.codes, alpha=.9, data=df, cmap="Set1", edgecolors='black', linewidths=.5)
# Add a graph in each part
sns.boxplot(df.hwy, ax=ax_right, orient="v")
sns.boxplot(df.displ, ax=ax_bottom, orient="h")
# Decorations ------------------
# Remove x axis name for the boxplot
ax_bottom.set(xlabel='')
ax_right.set(ylabel='')
# Main Title, Xlabel and YLabel
ax_main.set(title='Scatterplot with Histograms \n displ vs hwy', xlabel='displ', ylabel='hwy')
# Set font size of different components
ax_main.title.set_fontsize(20)
for item in ([ax_main.xaxis.label, ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):
item.set_fontsize(14)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment