12. Python3 使用matplotlib绘制图表

matplotlib 是一个数学绘图库, 可用来制作简单的图表, 如折线图和散点图等等.

mac


pip3 install --user matplotlib -i https://pypi.mirrors.ustc.edu.cn/simple/

测试 matplotlib

wushanghuideMacBook-Pro:~ wushanghui$ python3
Python 3.8.5 (default, Jul 21 2020, 10:48:26)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import matplotlib
>>>

matplotlib 画廊

查看使用matplotlib制作各种图表, 访问https://matplotlib.org/ 的示例画廊.

mpl_squares.py

import matplotlib.pyplot as plt

input_value = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

plt.plot(input_value, squares, linewidth=5)

plt.title("Square Numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)

plt.tick_params(axis='both', labelsize=14)

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TWVvhQaQ-1637590467400)(/upload/2020/11/image-0d9f61e69b7443bfafb181baaa799180.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9joy3Zv4-1637590467401)(/Users/wushanghui/Library/Application Support/typora-user-images/image-20201113215700983.png)]

scatter_squares.py

import matplotlib.pyplot as plt

x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]

plt.scatter(x_values, y_values, s=100)

plt.title("Square Numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)

plt.tick_params(axis='both', which='major', labelsize=14)

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7ab1bFg0-1637590467402)(/upload/2020/11/image-1949d34a254f4ede9ead0b029ee2dc7a.png)]

自动计算数据

scatter_squares2.py

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]

plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40)

plt.title("Square Numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)

plt.tick_params(axis='both', which='major', labelsize=14)

plt.axis([0, 1100, 0, 1100000])

plt.savefig('squares_plot.png', bbox_inches='tight')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7TC7NfMt-1637590467403)(/upload/2020/11/image-f0903e4c4cb2422bbfea53c55fd7a512.png)]

random_walk.py

from random import choice

class RandomWalk:
    """一个生成随机漫步数据的类"""

    def __init__(self, num_points=5000):
        """初始化随机漫步的属性"""
        self.num_points = num_points

        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        """计算随机漫步包含的所有点"""

        while len(self.x_values) < self.num_points:

            x_direction = choice([1, -1])

            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step == 0:
                continue

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

rw_visual.py

import matplotlib.pyplot as plt

from random_walk import RandomWalk

while True:

    rw = RandomWalk(50000)
    rw.fill_walk()

    plt.figure(dpi=256, figsize=(10, 6))

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)

    plt.scatter(0, 0, c='green', edgecolor='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolor='none', s=100)

    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("是否再模拟一次随机漫步?(y/n):")
    if keep_running == 'n':
        break

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K1oqvXYz-1637590467404)(/upload/2020/11/image-bb7714a2ad8547f8b59610b97231d356.png)]

Python3 目录

Original: https://blog.csdn.net/weixin_45847167/article/details/121482132
Author: 逆流者blog
Title: 12. Python3 使用matplotlib绘制图表

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/765897/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球