9.7 饼图

9.3 绘非线性图 - 图3

  1. pyplot.pie(x, explode=None, labels=None, colors=None,
  2. autopct=None, pctdistance=0.6, shadow=False,
  3. labeldistance=1.1, startangle=0, radius=1,
  4. counterclock=True, wedgeprops=None,
  5. textprops=None, center=(0, 0), frame=False,
  6. rotatelabels=False, *, normalize=True, data=None)

tiobe.txt
image.png

  1. import matplotlib.pyplot as plt
  2. def read_txt(filename):
  3. """接收文件名为参数,读取文件中的数据到二维列表中,返回二维列表。"""
  4. with open(filename, 'r', encoding='utf-8') as fr:
  5. data_lst = [line.strip().split(',') for line in fr] # 数据转列表
  6. return data_lst
  7. def pie_of_programs(data_lst):
  8. rank = [float(x[1]) for x in data_lst] # 百分比的列表
  9. plt.pie(rank)
  10. if __name__ == '__main__':
  11. file = 'tiobe.txt'
  12. data = read_txt(file)
  13. pie_of_programs(data)
  14. plt.show()

加标签
image.png

  1. def pie_of_programs(data_lst):
  2. prog_name = [x[0] for x in data_lst] # 语言名列表
  3. rank = [float(x[1]) for x in data_lst] # 百分比的列表
  4. plt.pie(rank, labels=prog_name)

image.png

  1. def pie_of_programs(data_lst, program): # program = 'Python'
  2. plt.axes(aspect=1) # 设置参数为1使饼图是圆的
  3. prog_name = [x[0] for x in data_lst] # 语言名列表
  4. rank = [float(x[1]) for x in data_lst] # 百分比的列表
  5. exp = [0] * len(prog_name) # 获得长度数据数量相同,元素为0的列表
  6. num = prog_name.index(program) # 获得数据python的序号
  7. exp[num] = 0.1 # 数据python突出显示
  8. plt.pie(rank, explode=exp, labels=prog_name, labeldistance=1.1,
  9. autopct='%2.1f%%', shadow=True, startangle=90,
  10. pctdistance=0.8)
  11. plt.legend(loc='lower right', bbox_to_anchor=(1.3, 0)) # 右下角例

9.8 直方图

9.3 绘非线性图 - 图7

  1. pyplot.hist(x, bins=None, range=None, density=False, weights=None,
  2. cumulative=False, bottom=None, histtype='bar', align='mid',
  3. orientation='vertical', rwidth=None, log=False, color=None,
  4. label=None, stacked=False, *, data=None, **kwargs)

x: (n,) array or sequence of (n,) arrays 数组或序列的数组
9.9 his.txt

  1. 95
  2. 68.25
  3. 99
  4. 100
  5. 94
  6. 98
  7. 97
  8. 84.5
  9. 84.5
  10. 92
  11. 89
  12. 77
  13. 74.5
  14. ......
  15. 94
  16. 85.5
  17. 88
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['FangSong'] # 支持中文显示
  4. plt.rcParams['axes.unicode_minus'] = False
  5. def read_csv(filename):
  6. """接收文件名为参数,读取文件中的数据到二维列表中,返回二维列表。"""
  7. with open(filename, 'r', encoding='utf-8') as fr:
  8. amount = [float(line) for line in fr]
  9. return amount
  10. def draw_hist(amount):
  11. """接收二维列表为参数,绘制数据曲线。"""
  12. amount_array = np.array(amount) # 列表amount转数组
  13. plt.hist(amount_array)
  14. if __name__ == '__main__':
  15. file = '9.9 his.txt'
  16. score_lst = read_csv(file)
  17. draw_hist(score_lst)
  18. plt.show()

image.png

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.rcParams['font.sans-serif'] = ['FangSong'] # 支持中文显示
  4. plt.rcParams['axes.unicode_minus'] = False
  5. def read_csv(filename):
  6. """接收文件名为参数,读取文件中的数据到二维列表中,返回二维列表。"""
  7. with open(filename, 'r', encoding='utf-8') as fr:
  8. amount = [float(line) for line in fr]
  9. return amount
  10. def draw_hist(amount):
  11. """接收二维列表为参数,绘制数据曲线。"""
  12. amount_array = np.array(amount) # 列表amount转数组
  13. plt.hist(amount_array, 20, color='g', edgecolor='b')
  14. def draw_label(): # 加图名和轴标签
  15. plt.xlabel('成绩')
  16. plt.title('成绩直方图')
  17. plt.ylabel('数量')
  18. plt.xticks(np.arange(0, 101, 10)) # X轴刻度
  19. plt.grid() # 显示网格线
  20. if __name__ == '__main__':
  21. file = '9.9 his.txt'
  22. score_lst = read_csv(file)
  23. draw_hist(score_lst)
  24. draw_label()
  25. plt.show()

9.9 散点图

  1. pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None,
  2. norm=None, vmin=None, vmax=None, alpha=None,
  3. linewidths=None, *, edgecolors=None,
  4. plotnonfinite=False, data=None, **kwargs)

x, yfloat or array-like, shape (n, )数据位置

import matplotlib.pyplot as plt

def read_file(file):
    with open(file, 'r') as f:
        ls = [x.strip().split(',') for x in f]  # 读逗号分隔数据
    return ls


def plot_scatter(ls):
    # 分别取出男生身高和体重两列数据
    boy_height = [float(x[1]) for x in ls if int(x[0]) == 1]  # 男生身高数据
    boy_weight = [float(x[2]) for x in ls if int(x[0]) == 1]  # 男生体重数据
    plt.scatter(boy_height, boy_weight)


if __name__ == '__main__':
    filename = '9.11 health.csv'
    data_lst = read_file(filename)
    plot_scatter(data_lst)
    plt.show()

image.pngimage.png

def plot_scatter(ls):
    # 分别取出男生身高和体重两列数据
    boy_height = [float(x[1]) for x in ls if int(x[0]) == 1]  # 男生身高数据
    boy_weight = [float(x[2]) for x in ls if int(x[0]) == 1]  # 男生体重数据
    plt.scatter(boy_height, boy_weight)
    plt.xlim(105, 160)  # x取值范围设置
    plt.ylim(15, 50)    # y取值范围设置
def plot_scatter(ls):
    # 分别取出男生身高和体重两列数据
    boy_height = [float(x[1]) for x in ls if int(x[0]) == 1]   # 男生身高数据
    boy_weight = [float(x[2]) for x in ls if int(x[0]) == 1]   # 男生体重数据
    plt.scatter(boy_height, boy_weight, c='b', marker=(5, 1))  # 蓝颜色,五角星,同*
    girl_height = [float(x[1]) for x in ls if int(x[0]) == 2]  # 女生身高数据
    girl_weight = [float(x[2]) for x in ls if int(x[0]) == 2]  # 女生体重数据
    plt.scatter(girl_height, girl_weight, c='g')               # 绿颜色,默认圆点
    plt.xlim(105, 160)  # x取值范围设置
    plt.ylim(15, 50)    # y取值范围设置

image.png

9.10 等值线图

9.3 绘非线性图 - 图12

pyplot.contour(*args, data=None, **kwargs)

X, Yarray-like, optional类似数组的数据
用于获取 Z值的2D坐标.
Z(M, N) array-like 类似数组的数据

import matplotlib.pyplot as plt
import numpy as np


def f(x, y):
    """接受两个数值类型数据为参数,计算表达式结果并返回。"""
    return (1 - 7 * x / 2 + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)


def plot_contour():
    x0 = np.linspace(-3, 3, 256)
    y0 = np.linspace(-3, 3, 256)
    m, n = np.meshgrid(x0, y0)
    C = plt.contour(m, n, f(m, n), 18, colors='blue')  # 绘制等值线,蓝色
    plt.clabel(C, inline=1, fontsize=10)  # 在等高线上绘制高程值
    plt.xticks([])  # 设定x轴无刻度
    plt.yticks([])  # 设定y轴无刻度
    plt.show()


if __name__ == '__main__':
    plot_contour()
    plt.show()

9.11 曲线拟合

scipy.optimize.curve_fit(f,xdata,ydata,p0=None,sigma=None,
                         absolute_sigma=False,check_finite=True,
                         bounds=(-inf,inf),method=None,jac=None,**kwargs)

9.3 绘非线性图 - 图13

# 曲线拟合
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize


# 直线方程函数
def fun1(x, A, B):
    return A * x + B


# 二次曲线方程
def fun2(x, A, B, C):
    return A * x * x + B * x + C


# 三次曲线方程
def fun3(x, A, B, C, D):
    return A * x * x * x + B * x * x + C * x + D


def plot_scatter():
    plt.scatter(x0[:], y0[:], 25, "red")  # 绘制散点


def linear_fit():    # 直线拟合与绘制
    A1, B1 = optimize.curve_fit(fun1, x0, y0)[0]
    x1 = np.arange(0, 6, 0.01)
    y1 = A1 * x1 + B1
    plt.plot(x1, y1, "blue")


def quadratic_fit():    # 二次曲线拟合与绘制
    A2, B2, C2 = optimize.curve_fit(fun2, x0, y0)[0]
    x2 = np.arange(0, 6, 0.01)
    y2 = A2 * x2 * x2 + B2 * x2 + C2
    plt.plot(x2, y2, "green")


def cubic_fit():    # 三次曲线拟合与绘制
    A3, B3, C3, D3 = optimize.curve_fit(fun3, x0, y0)[0]
    x3 = np.arange(0, 6, 0.01)
    y3 = A3 * x3 * x3 * x3 + B3 * x3 * x3 + C3 * x3 + D3
    plt.plot(x3, y3, "purple")


def add_label():
    plt.title("曲线拟合", fontproperties="SimHei")
    plt.xlabel('x')
    plt.ylabel('y')


if __name__ == '__main__':
    x0 = [1, 2, 3, 4, 5]
    y0 = [1, 3, 8, 18, 36]
    plot_scatter()
    linear_fit()
    quadratic_fit()
    cubic_fit()
    add_label()
    plt.show()

9.12 雷达图

9.3 绘非线性图 - 图14
9.10 scoreRadar.txt

import matplotlib.pyplot as plt
import numpy as np

# 支持中文显示
plt.rcParams['font.sans-serif'] = ['FangSong']  # 仿宋
plt.rcParams['axes.unicode_minus'] = False


def read_csv(file):  # 读文件为列表类型
    with open(file, 'r', encoding='utf-8') as data:
        ls = [line.strip().split('\t') for line in data]
        return ls


def plot_radar(score):
    """接收二维列表为参数,绘制雷达图曲线。"""
    labels = np.array(score)[0, 1:]  # 序号0的行中序号1以后的列作标签
    data_lenth = 5  # 数据个数
    cl = ['b', 'g', 'r']  # 线条颜色
    angles = np.linspace(0, 2 * np.pi, data_lenth, endpoint=False)  # [0,2]分5份
    angles = np.append(angles, [angles[0]])  # 加上起点,闭合折线
    fig = plt.figure()  # 创建画布
    ax = fig.add_subplot(111, polar=True)  # 创建子图,极坐标
    for i in range(1, 4):  # 逐条绘制各专业曲线
        score_new = np.array(score[i][1:]).astype(int)  # 第i个专业成绩
        data = np.append(score_new, [score_new[0]])  # 闭合曲线
        ax.plot(angles, data, color=cl[i - 1], linewidth=2)  # 画线
        ax.set_thetagrids(angles[:-1] * 180 / np.pi, labels)
    ax.set_title("成绩雷达图", va='bottom')
    ax.set_rlim(0, 100)  # 径向刻度标签
    ax.grid(True)  # 显示网格线


if __name__ == '__main__':
    file = '9.10 scoreRadar.txt'
    score_lst = read_csv(file)
    plot_radar(score_lst)
    plt.show()

9.13 柱形图

2021年末全国地铁里程排名

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['FangSong']  # 支持中文显示
plt.rcParams['axes.unicode_minus'] = False
metro = {'上海': 825, '北京': 783, '广州': 590, '成都': 558, '武汉': 479, '深圳': 431, '南京': 427, '重庆': 402, '杭州': 401, '青岛': 293}

x = list(metro.keys())
y = list(metro.values())
plt.bar(x, y, width=1, edgecolor="white", linewidth=0.7)
plt.xticks(x)
plt.yticks(range(0, 950, 100))
for x, y in metro.items():
    plt.text(x, y + 10, "%s" % y)
plt.title('截至2022年5月全国轨道交通里程top 10')
plt.show()

image.pngimage.png