Python / Data Science Essentials Interview Questions
How do you control colours and colour palettes in Matplotlib and Seaborn?
Colour is one of the most impactful design decisions in a chart. Used correctly it encodes information; used poorly it confuses or misleads. Both Matplotlib and Seaborn give you fine-grained control.
import matplotlib.pyplot as plt import seaborn as sns import numpy as np # --- Matplotlib colour specifications --- # Named CSS colours plt.plot(x, y, color='steelblue') # Hex string plt.plot(x, y, color='#2E86AB') # RGB tuple (values 0-1) plt.plot(x, y, color=(0.18, 0.52, 0.67)) # Grayscale string plt.plot(x, y, color='0.5') # 50% grey # --- Colormaps for continuous data --- im = plt.imshow(matrix, cmap='viridis') # perceptually uniform plt.colorbar(im) # Other good cmaps: 'plasma', 'inferno', 'magma' (sequential) # 'RdBu', 'coolwarm', 'bwr' (diverging â centred on 0) # 'tab10', 'Set1', 'Set2' (categorical) # --- Seaborn palettes --- # Categorical (qualitative) sns.barplot(data=df, x='day', y='tip', palette='Set2') # Sequential (one colour family) sns.barplot(data=df, x='day', y='tip', palette='Blues_d') # Diverging (two colour families around a midpoint) sns.heatmap(corr, cmap='coolwarm', vmin=-1, vmax=1, center=0) # Custom palette custom = ['#E63946', '#457B9D', '#1D3557', '#A8DADC'] sns.barplot(data=df, x='day', y='tip', palette=custom) # Preview a palette sns.palplot(sns.color_palette('husl', 8))
Always use perceptually uniform colormaps (viridis, plasma) for continuous data — rainbow/jet maps are misleading because they are not perceptually linear (the eye perceives the yellow band as brighter than the blue or red bands, creating false visual contrast). For diverging data (correlation matrices, residuals) use a diverging colormap centred on zero.
More Related questions...