In this article Data Visualization in Python Learn how to create and visualize 2D and 3D graphics in Python using Matplotlib. Understand different plotting techniques like line, scatter, bar, surface, and contour plots with examples for students and beginners.

Data visualization — plotting common 2D and 3D graphics (with Python examples)

Data visualization turns numbers into insight. Below is a compact, practical guide to plotting common 2D and 3D charts you’ll use in data analysis, machine learning, or reporting — with ready-to-run Python examples using matplotlib, seaborn, and plotly. Copy–paste the snippets into a Jupyter notebook or a .py file (for interactive 3D use Jupyter or a browser-backed environment).

Quick notes before you start

  • matplotlib = foundational plotting library (static plots suitable for reports).
  • seaborn = high-level API built on matplotlib (great defaults for statistical plots).
  • plotly = interactive plots (browser-based, good for 3D interactive visuals).
  • In Jupyter: use %matplotlib inline (static) or %matplotlib notebook / %matplotlib widget for interactivity. For plotly use plotly.express or plotly.graph_objects.
  • Always label axes, give titles, and include legends where applicable.
  • Save figures with plt.savefig(“name.png”, dpi=300) for publication-quality images.

Install (if needed):

pip install matplotlib seaborn plotly

1 — Basic 2D plots (matplotlib)

1.1 Line plot

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(0, 10, 200)

y = np.sin(x) * np.exp(-x/6)

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

plt.plot(x, y, label=’damped sine’, linewidth=2)

plt.title(“Line plot: Damped sine”)

plt.xlabel(“x”)

plt.ylabel(“y”)

plt.grid(alpha=0.3)

plt.legend()

plt.tight_layout()

plt.show()

1.2 Scatter plot

import matplotlib.pyplot as plt

import numpy as np

rng = np.random.default_rng(1)

x = rng.normal(0, 1, 200)

y = 2.0*x + rng.normal(0, 0.8, 200)

sizes = 20 + 80 * rng.random(200)

colors = rng.random(200)

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

plt.scatter(x, y, s=sizes, c=colors, cmap=’viridis’, alpha=0.7)

plt.colorbar(label=’color scale’)

plt.title(“Scatter plot”)

plt.xlabel(“x”)

plt.ylabel(“y”)

plt.show()

1.3 Bar chart (categorical)

labels = [‘A’,’B’,’C’,’D’]

values = [23, 45, 12, 37]

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

plt.bar(labels, values, color=[‘#4c72b0′,’#dd8452′,’#55a868′,’#c44e52’])

plt.title(“Bar chart”)

plt.ylabel(“Value”)

plt.show()

1.4 Histogram

data = np.random.normal(loc=50, scale=10, size=1000)

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

plt.hist(data, bins=30, edgecolor=’k’, alpha=0.7)

plt.title(“Histogram”)

plt.xlabel(“Value”)

plt.ylabel(“Frequency”)

plt.show()

1.5 Boxplot (with seaborn)

import seaborn as sns

import pandas as pd

df = pd.DataFrame({

    ‘group’: np.repeat([‘G1′,’G2′,’G3’], 100),

    ‘value’: np.concatenate([np.random.normal(10,2,100),

                             np.random.normal(12,3,100),

                             np.random.normal(9,1.5,100)])

})

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

sns.boxplot(x=’group’, y=’value’, data=df)

plt.title(“Boxplot by group”)

plt.show()

1.6 Heatmap (correlation)

import seaborn as sns

import pandas as pd

df = pd.DataFrame(rng.normal(size=(100,5)), columns=list(‘ABCDE’))

corr = df.corr()

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

sns.heatmap(corr, annot=True, fmt=”.2f”, cmap=’coolwarm’, vmin=-1, vmax=1)

plt.title(“Correlation heatmap”)

plt.show()

2 — Statistical & specialized plots (seaborn)

Seaborn makes it easy to produce attractive stats plots.

sns.pairplot(df, kind=’scatter’, diag_kind=’kde’, corner=True)

plt.show()

sns.violinplot(x=’group’, y=’value’, data=df)

plt.title(“Violin plot”)

plt.show()

3 — 3D plots (matplotlib) — good for static 3D

3.1 3D surface plot

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import numpy as np

X = np.linspace(-3, 3, 80)

Y = np.linspace(-3, 3, 80)

X, Y = np.meshgrid(X, Y)

Z = np.sin(np.sqrt(X**2 + Y**2)) / (1 + 0.1*(X**2 + Y**2))

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

ax = fig.add_subplot(111, projection=’3d’)

surf = ax.plot_surface(X, Y, Z, cmap=’viridis’, edgecolor=’none’, linewidth=0, antialiased=True)

fig.colorbar(surf, shrink=0.6)

ax.set_title(“3D Surface”)

plt.show()

3.2 3D scatter

fig = plt.figure(figsize=(7,6))

ax = fig.add_subplot(111, projection=’3d’)

z = rng.normal(size=200)

x = rng.normal(size=200)

y = rng.normal(size=200)

ax.scatter(x, y, z, c=z, cmap=’coolwarm’, s=40, alpha=0.8)

ax.set_title(“3D Scatter”)

plt.show()

Matplotlib 3D is static (image). For interactive rotation/zoom use plotly or Jupyter widgets.

4 — Interactive 2D & 3D (plotly) — recommended for exploration

Install: pip install plotly

4.1 Interactive line & scatter (plotly.express)

import plotly.express as px

import pandas as pd

df_px = pd.DataFrame({‘x’: x, ‘y’: y})

fig = px.scatter(df_px, x=’x’, y=’y’, title=”Interactive scatter (plotly)”)

fig.show()

4.2 Interactive 3D surface (plotly)

import plotly.graph_objects as go

fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y)])

fig.update_layout(title=’Interactive 3D Surface’, autosize=True,

                  scene=dict(xaxis_title=’X’, yaxis_title=’Y’, zaxis_title=’Z’))

fig.show()

4.3 Interactive 3D scatter

fig = px.scatter_3d(x=x, y=y, z=z, color=z, size=np.abs(z), title=”Interactive 3D scatter”)

fig.show()

5 — Practical tips & best practices

  • Choose chart type based on data: continuous → line/histogram; categorical → bar; relationships → scatter; distributions → box/violin.
  • Avoid clutter: keep plots focused, limit colors and labels.
  • Color maps: use perceptually uniform maps (e.g., viridis) for numeric scales.
  • Legibility: increase font sizes for presentations (plt.rcParams.update({‘font.size’: 12})).
  • Save vector graphics for print: plt.savefig(‘plot.svg’) or plt.savefig(‘plot.pdf’).
  • Interactive reporting: use plotly for dashboards or matplotlib for static figures in papers.
  • Large datasets: use alpha blending, hexbin plots (plt.hexbin) or downsample for speed.
  • Reproducibility: set random seeds and annotate figure code to reproduce visuals.

6 — Short example: combine many plots in one figure

fig, axes = plt.subplots(2,2, figsize=(10,7))

axes = axes.ravel()

axes[0].plot(x, np.sin(x))

axes[0].set_title(“Sine”)

axes[1].hist(data, bins=30)

axes[1].set_title(“Histogram”)

axes[2].scatter(x, y, alpha=0.6)

axes[2].set_title(“Scatter”)

sns.boxplot(x=’group’, y=’value’, data=df, ax=axes[3])

axes[3].set_title(“Boxplot”)

plt.tight_layout()

plt.show()

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

https://defineinfoloop.blogspot.com/?m=1

Leave a Reply

Your email address will not be published. Required fields are marked *