25 个常用 Matplotlib 图的 Python 代码,值得收藏!

2024-12-31 09:53:05   小编

25 个常用 Matplotlib 图的 Python 代码,值得收藏!

Matplotlib 是 Python 中一个强大的数据可视化库,能够创建各种类型的图表。以下为您分享 25 个常用的 Matplotlib 图的 Python 代码示例。

1. 折线图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.show()

2. 柱状图

import matplotlib.pyplot as plt

x = ['A', 'B', 'C', 'D', 'E']
y = [10, 20, 30, 40, 50]

plt.bar(x, y)
plt.show()

3. 饼图

import matplotlib.pyplot as plt

labels = ['Apple', 'Banana', 'Orange', 'Mango']
sizes = [15, 30, 45, 10]

plt.pie(sizes, labels=labels)
plt.show()

4. 散点图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.scatter(x, y)
plt.show()

5. 直方图

import matplotlib.pyplot as plt

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

plt.hist(data)
plt.show()

6. 箱线图

import matplotlib.pyplot as plt

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

plt.boxplot(data)
plt.show()

7. 面积图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 5, 10, 17, 26]

plt.fill_between(x, y1, y2)
plt.show()

8. 堆叠柱状图

import matplotlib.pyplot as plt

x = ['A', 'B', 'C']
y1 = [10, 20, 30]
y2 = [5, 10, 15]

plt.bar(x, y1)
plt.bar(x, y2, bottom=y1)
plt.show()

9. 双轴图

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 5, 10, 17, 26]

fig, ax1 = plt.subplots()

ax1.plot(x, y1)
ax2 = ax1.twinx()
ax2.plot(x, y2, color='r')

plt.show()

10. 极坐标图

import matplotlib.pyplot as plt

theta = [0, 30, 45, 60, 90]
r = [1, 2, 3, 4, 5]

plt.polar(theta, r)
plt.show()

(此处省略部分代码示例)

通过以上 25 个常用的 Matplotlib 图的 Python 代码示例,您可以轻松地根据数据需求创建出直观、清晰的图表,更好地进行数据分析和展示。希望这些代码能够对您的工作和学习有所帮助。

TAGS: Python 代码 值得收藏 Matplotlib 图 常用图表

欢迎使用万千站长工具!

Welcome to www.zzTool.com