Loading

Quipoin Menu

Learn • Practice • Grow

python-for-ai / Histograms and Scatter Plots
interview

Q1. Generate 1000 random numbers from a normal distribution and plot a histogram with 30 bins. Also plot the kernel density estimate.
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

data = np.random.randn(1000)
plt.hist(data, bins=30, density=True, alpha=0.6)
kde = gaussian_kde(data)
x = np.linspace(-4,4,200)
plt.plot(x, kde(x), color=''red'')
plt.show()

Q2. Create a scatter plot of x and y data: x = [1,2,3,4,5], y = [2,4,5,4,3]. Add regression line using numpy polyfit.
plt.scatter(x, y)
coeffs = np.polyfit(x, y, 1)
line = np.poly1d(coeffs)
plt.plot(x, line(x), color=''red'')
plt.show()
Scatter plots show relationship between two variables.

Q3. Color scatter points by a third variable (size or color) using c parameter. Use a colormap.
plt.scatter(x, y, c=z, cmap=''viridis'')
plt.colorbar(label=''Z value'')
plt.show()
Useful for visualizing clusters or gradients.

Q4. Plot two histograms on the same axes with transparency to compare distributions of two datasets.
plt.hist(data1, bins=20, alpha=0.5, label=''Data1'')
plt.hist(data2, bins=20, alpha=0.5, label=''Data2'')
plt.legend()
plt.show()
Alpha controls transparency.

Q5. Use plt.subplots to create a 1x2 grid of plots: left histogram, right scatter.
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4))
ax1.hist(data)
ax1.set_title(''Histogram'')
ax2.scatter(x, y)
ax2.set_title(''Scatter'')
plt.tight_layout()
plt.show()