Fundamentals 10 min read

17 Essential Python Plotting Code Snippets for Beginners

This tutorial provides 17 practical Python plotting examples—from basic line and bar charts to 3D visualizations and real‑time updates—complete with ready‑to‑run code snippets using Matplotlib, Seaborn, and Plotly, helping newcomers quickly master data visualization techniques.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
17 Essential Python Plotting Code Snippets for Beginners

This article presents 17 essential Python plotting examples for beginners, covering a wide range of chart types and techniques.

1. Plot a straight line

Creates a simple line from (0,0) to (1,1).

import matplotlib.pyplot as plt
x = [0, 1]
y = [0, 1]
plt.plot(x, y)
plt.show()

2. Draw a rectangle

Uses Matplotlib patches to add a rectangle to a subplot.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots()
rect = patches.Rectangle((0.1, 0.1), 0.5, 0.5, linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()

3. Bar chart

Compares values across categories.

import matplotlib.pyplot as plt
x = ["A", "B", "C", "D", "E"]
y = [10, 15, 7, 12, 9]
plt.bar(x, y)
plt.title("柱状图示例")
plt.xlabel("类别")
plt.ylabel("数值")
plt.show()

4. Line chart

Shows trends over a sequence.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [5, 3, 7, 2, 6]
plt.plot(x, y)
plt.title("折线图示例")
plt.xlabel("X轴")
plt.ylabel("Y轴")
plt.show()

5. Pie chart

Displays proportion of categories.

import matplotlib.pyplot as plt
labels = ["A", "B", "C", "D"]
sizes = [30, 20, 25, 15]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("饼图示例")
plt.show()

6. Scatter plot

Shows relationship between two variables using Seaborn.

import seaborn as sns
import pandas as pd
data = {'x': [1, 2, 3, 4, 5], 'y': [10, 15, 7, 12, 9]}
df = pd.DataFrame(data)
sns.scatterplot(x='x', y='y', data=df)
plt.title("散点图示例")
plt.show()

7. Box plot

Visualizes data distribution.

import seaborn as sns
import pandas as pd
data = {'value': [10, 15, 7, 12, 9, 18, 20]}
df = pd.DataFrame(data)
sns.boxplot(y='value', data=df)
plt.show()

8. Heatmap

Displays density of a 2‑D dataset.

import seaborn as sns
import pandas as pd
import numpy as np
data = np.random.rand(10, 10)
df = pd.DataFrame(data)
sns.heatmap(df)
plt.title("热力图示例")
plt.show()

9. Contour plot

Shows 2‑D contour lines of a 3‑D function.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
plt.contour(X, Y, Z)
plt.title("等高线图示例")
plt.show()

10. Add legend

Labels multiple curves for clarity.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 5, 10, 17]
plt.plot(x, y1, label='曲线 1')
plt.plot(x, y2, label='曲线 2')
plt.legend()
plt.show()

11. Change color

Enhances visual appeal by setting line color.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y, color='orange')
plt.show()

12. Plot from CSV file

Reads a CSV and plots date vs. sales.

import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data.csv')
plt.plot(data['日期'], data['销量'])
plt.title("销量趋势图")
plt.xlabel("日期")
plt.ylabel("销量")
plt.show()

13. Simple interactivity with Plotly

Creates an interactive bar chart.

import plotly.express as px
import pandas as pd
data = {'水果': ['苹果', '香蕉', '橙子'], '数量': [10, 15, 8]}
df = pd.DataFrame(data)
fig = px.bar(df, x='水果', y='数量')
fig.show()

14. 3D scatter plot

Displays points in three‑dimensional space.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
ax.scatter(x, y, z)
plt.title("3D 散点图示例")
plt.show()

15. 3D surface plot

Shows a 3‑D surface of a sine function.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
plt.title("3D 曲面图示例")
plt.show()

16. Subplots

Displays multiple plots in one figure for comparison.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axs = plt.subplots(2)
fig.suptitle('子图示例')
axs[0].plot(x, y1)
axs[0].set_title('正弦函数')
axs[1].plot(x, y2)
axs[1].set_title('余弦函数')
plt.show()

17. Real‑time updating plot

Simulates dynamic data such as temperature changes.

import matplotlib.pyplot as plt
import numpy as np
import time
fig, ax = plt.subplots()
x, y = [], []
line, = ax.plot(x, y)
for i in range(10):
    x.append(i)
    y.append(np.random.rand())
    line.set_data(x, y)
    ax.relim()
    ax.autoscale_view()
    plt.pause(0.5)
plt.show()

Conclusion: Try the code snippets and explore Python’s powerful visualization libraries.

TutorialData VisualizationMatplotlibPlotlyseabornPlotting
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.