Lesson 40 · Data visualisation in python
Creating 3D and Animated Data Visualizations in Python with Matplotlib and Plotly
You have learned how to: Create 3D scatter plots, lines, and surfaces. Animate charts in 2D and 3D. Use real datasets for scientific and weather patterns.…
- CourseData visualisation in python
- Lesson40 of 34
- Video14 min
- FormatJupyter notebook · 0 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbRecap: You Did It!#
You have learned how to:
- Create 3D scatter plots, lines, and surfaces.
- Animate charts in 2D and 3D.
- Use real datasets for scientific and weather patterns.
- Add extra style, save your work, and solve common errors.
- If plots do not show, try running
%matplotlib inlineagain. - Check your spelling of column names and functions.
- Animations sometimes do not show unless you run Notebook cells slowly.
Save your figures if you want to keep them!
ax.scatter(years, sun, trend, c=sun, cmap='coolwarm', marker='^') ax.set_xlabel('Year') ax.set_ylabel('Sunspots') ax.set_zlabel('Trend') ax.view_init(elev=30, azim=140) plt.title('Custom 3D Sunspots View') plt.show()
ax.set_xlabel('Year') ax.set_ylabel('Sunspots') ax.set_zlabel('Trend')
def animate3d(i): ax.clear() ax.set_xlabel('Year') ax.set_ylabel('Sunspots') ax.set_zlabel('Trend') ax.set_title('Animated 3D Sunspots Scatter') ax.scatter(years[:i], sun[:i], trend[:i], c=sun[:i], cmap='plasma')
ani3d = animation.FuncAnimation(fig, animate3d, frames=len(years)//20, interval=30, blit=False) plt.show()
ax.set_xlim(years.min(), years.max()) ax.set_ylim(sun.min(), sun.max()) line, = ax.plot([], [], lw=2) ax.set_title('Monthly Sunspot Animation') ax.set_xlabel('Year') ax.set_ylabel('Mean Sunspots')
def init(): line.set_data([], []) ## Next Steps & YouTube
Keep practicing: try different datasets, styles, or variables.
Want more lessons? Subscribe and hit the notification bell to stay up to date with Python skill videos!
Tell us in the comments what you would like to learn next.
temp_df = pd.read_csv(daily_url) temp_df['Date'] = pd.to_datetime(temp_df['Date']) temp_df['Month'] = temp_df['Date'].dt.month monthly_avg = temp_df.groupby('Month')['Temp'].mean()
3D Surface: Seasons vs. Day vs. Temp#
X2, Y2 = np.meshgrid(np.arange(1,13), np.arange(1,32)) Z2 = np.zeros_like(X2, dtype=float) for m in range(1,13): days = temp_df[temp_df['Month']==m] for d in range(1,32): vals = days[days['Date'].dt.day==d]['Temp'] if not vals.empty: Z2[d-1, m-1] = vals.mean()
Plot 3D surface for average temperature#
fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111, projection='3d') surf = ax.plot_surface(X2, Y2, Z2, cmap='winter', edgecolor='none') ax.set_xlabel('Month') ax.set_ylabel('Day') ax.set_zlabel('Avg Temp (C)') plt.title('Seasonal 3D Temperature Surface (Melbourne, 1981-1990)') plt.colorbar(surf, shrink=0.5, aspect=10) plt.show()
plt.title('3D Line: Sunspots History Curve') plt.show() Examples are surfaces (like hills), climate maps, or showing cycles over time. ax = fig.add_subplot(111, projection='3d') years = ds['YEAR'] + (ds['MONTH']-1)/12 sun = ds['SUNACTIVITY'] trend = np.linspace(sun.min(), sun.max(), len(sun)) ax.scatter(years, sun, trend, c=sun, cmap='plasma', marker='o') ax.set_xlabel('Year') ax.set_ylabel('Sunspots') ax.set_zlabel('Trend') plt.title('3D Scatter Plot of Sunspot Data') plt.show()
Look at the shape and first few rows#
print("Shape:", ds.shape) ds.head() Let us load the data and take a quick look before plotting.
import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation
Enable plots to show inside the notebook#
%matplotlib inline
- How to make 3D plots in Python.
- Where to find and load real datasets.
- Simple ways to animate your charts.
- Some tips to make your plots clearer and more fun.
First look: Plot sunspot numbers over time#
plt.figure(figsize=(10,4)) plt.plot(ds['YEAR'] + (ds['MONTH']-1)/12, ds['SUNACTIVITY']) plt.xlabel('Year') plt.ylabel('Mean Sunspots')
Extra: Animate the temperature surface by month#
fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111, projection='3d')
def surface_anim(i): ax.clear() ax.set_xlabel('Month') ax.set_ylabel('Day') ax.set_zlabel('Avg Temp (C)') ax.set_title(f'Month {i+1}') surf = ax.plot_surface(X2[:,i:i+1], Y2[:,i:i+1], Z2[:,i:i+1], cmap='autumn', edgecolor='k')
ani_temp = animation.FuncAnimation(fig, surface_anim, frames=12, interval=500, blit=False) plt.show() x = np.linspace(0, 20, 100) y = np.linspace(0, 10, 80) X, Y = np.meshgrid(x, y) Z = np.sin(X) * np.cos(Y) fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111, projection='3d') surf = ax.plot_surface(X, Y, Z, cmap='viridis') plt.title('3D Surface Example') fig.colorbar(surf, shrink=0.5, aspect=10) plt.show()
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



