[Python]常用画图函数

本文介绍了使用Python进行数据可视化的多种方法,包括单线图、多线图、水平条形图、堆叠条形图及饼图等。通过具体实例展示了如何利用matplotlib库绘制不同类型的图表,并对每种图表的参数进行了详细解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用画图函数(Python)

Requirements

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Colors array

colors = ['lightcoral', 'teal', 'chartreuse', 'lightskyblue', 'mediumorchid', 'salmon', 'orangered',
          'darkgreen', 'darkmagenta', 'cyan', 'tomato', 'goldenrod', 'mistyrose', 'peru', 'black', 'blue', 'lightblue',
          'lavender', 'darkorange', 'yellowgreen', 'deepskyblue', 'forestgreen', 'green', 'seagreen', 'darkviolet',
          'maroon', 'burlywood', 'lawngreen', 'springgreen', 'violet', 'mediumturquoise', 'lime', 'darkorchid',
          'palegoldenrod', 'hotpink', 'skyblue', 'olive', 'gainsboro', 'floralwhite', 'cadetblue', 'azure',
          'lightslategray', 'navajowhite', 'navy', 'thistle', 'coral', 'lavenderblush', 'seashell', 'aquamarine',
          'khaki', 'sandybrown', 'aqua', 'midnightblue', 'lightsteelblue', 'moccasin', 'bisque', 'sienna', 'steelblue',
          'darkseagreen', 'darksalmon', 'darkkhaki', 'lightsalmon', 'indianred', 'lightgreen', 'mediumslateblue',
          'peachpuff', 'papayawhip', 'ivory', 'fuchsia', 'slateblue', 'beige', 'olivedrab', 'crimson', 'yellow',
          'lightseagreen', 'deeppink', 'greenyellow', 'darkblue', 'magenta', 'mediumvioletred', 'blueviolet', 'tan',
          'mediumaquamarine', 'darkgoldenrod', 'purple', 'snow', 'mediumblue', 'slategray', 'saddlebrown',
          'lightgoldenrodyellow', 'darkred', 'turquoise', 'darkslateblue', 'darkslategray', 'darkcyan',
          'blanchedalmond', 'ghostwhite', 'cornsilk', 'paleturquoise', 'lemonchiffon', 'linen', 'indigo', 'gold',
          'palegreen', 'wheat', 'orchid', 'royalblue', 'cornflowerblue', 'darkturquoise', 'firebrick', 'silver',
          'darkolivegreen', 'dodgerblue', 'chocolate', 'red', 'mintcream', 'white', 'plum', 'palevioletred',
          'lightcyan', 'orange', 'rosybrown', 'lightpink', 'antiquewhite', 'lightgray', 'brown', 'gray', 'limegreen',
          'dimgray', 'lightyellow', 'honeydew', 'aliceblue', 'mediumspringgreen', 'whitesmoke', 'mediumseagreen',
          'oldlace', 'pink', 'powderblue', 'mediumpurple']

Plot Single Line

def plot_line(x=np.arange(10),
              y=np.arange(10)):
    """
    Plot a single line.
    :param x: data array
    :param y: label array
    :return: None
    """
    plt.figure()
    plt.plot(x, y, 'bo', linestyle='-')
    plt.title('{}'.format('Title'))
    plt.xlabel('{}'.format('x label'), fontsize=14)
    plt.ylabel('{}'.format('y label'), fontsize=10)
    plt.show()

Plot Multi-lines

def plot_multi_lines(df=pd.DataFrame(index=['1', '2'],
                                     data=[[1, 2], [3, 4]],
                                     columns=['c1', 'c2'])):
    """
    Plot multi lines in a figure.
    :param df: DataFrame
    :return: None
    """
    plt.figure()
    df.plot(figsize=(12, 8), title='{}'.format('Title'))
    plt.show()

Plot barh

def plot_barh(records=np.array([1, 2]),
              labels=np.array(['label-1', 'label-2'])):
    """
    :param records: Data Array
    :param labels: Label Array
    :return: None
    """
    plt.rcParams['axes.facecolor'] = 'white'
    x = np.arange(len(records))
    plt.subplots(figsize=(4, 2))
    plt.barh(x, records, align="center", alpha=0.3, height=0.4)
    plt.title('{}'.format('Title'))
    plt.yticks(x, labels)
    plt.ylim(-1, x[-1] + 1)
    plt.xlabel('{}'.format('X label'))
    plt.show()

Plot multi-barh

def plot_multi_barh(records=np.ones((4, 4)),
                    label=np.array(['label-{}'.format(x) for x in np.arange(4)]),
                    width=0.2,
                    alpha=0.7,
                    figsize=(20, 10),
                    xlim=1,
                    ylim=0.3):
    """
    Plot Multi barh in a figure.
    :param records: Data Matrix.
    :param label: Label Array
    :param width: the width of each bar.
    :param alpha: Color alpha.
    :param figsize: Figure size.
    :param xlim:
    :param ylim:
    :return: None
    """
    ind = np.arange(len(label))
    fig, ax = plt.subplots(figsize=figsize)
    ax_array = []

    for i in range(records.shape[0]):
        ax_array.append(ax.barh(ind + i * width, records[i], width, color=colors[i], alpha=alpha))

    ax.set_yticks(ind + 2 * width)
    ax.set_yticklabels(label)
    plt.ylim(-1, len(ind) + ylim)
    plt.xlim(0, np.max(records) + xlim)
    ax.legend(([each[0] for each in ax_array]), label, loc='best')
    plt.show()

Plot Stack Bar

def plot_stack_bar(records=np.ones(shape=(4, 5)),
                   legend_labels=np.array(['color-{}'.format(x) for x in np.arange(5)]),
                   index_label=np.array(['index-{}'.format(x) for x in np.arange(4)]),
                   width=0.4,
                   alpha=0.3,
                   ylabel='ylabel',
                   xlabel='xlabel',
                   title='title',
                   figsize=(24, 10),
                   normalize=False):
    def norm_data(records):
        for i in range(records.shape[0]):
            total = np.sum(records[i][:])
            for j in range(records.shape[1]):
                records[i][j] /= total

    if normalize:
        norm_data(records)
    fig = plt.figure(figsize=figsize, facecolor="white")
    ax = fig.add_subplot(1, 1, 1)
    ind = np.arange(records.shape[0])
    axs_array = []
    bottom_array = np.zeros(records.shape[0])
    for i in range(records.shape[1]):
        axs_array.append(ax.bar(ind,
                                records[:, i],
                                width=width,
                                color=colors[i],
                                bottom=bottom_array,
                                align='center',
                                alpha=alpha
                                ))
        bottom_array = bottom_array + records[:, i]

    # for i in range(records.shape[0]):
    #     for j in range(records.shape[1]):
    #         plt.text(i, np.sum(records[i, 0: (j + 1)]),
    #                  round(records[i][j], 2),
    #                  ha="center")

    plt.ylabel('{}'.format(ylabel), fontsize=20)
    plt.title('{}'.format(title), fontsize=20)
    plt.xlabel('{}'.format(xlabel), fontsize=20)
    plt.xticks(ind, index_label, rotation=40)
    plt.legend(([each[0] for each in axs_array]),
               legend_labels,
               loc='best')
    plt.show()

Plot Pie

def plot_pie(data=np.ones(10),
             labels=['index-{}'.format(x) for x in np.arange(10)]):
    sizes = [360 * each / np.sum(data) for each in data]
    plt.pie(sizes,
            labels=labels,
            autopct='%1.1f%%',
            startangle=0,
            colors=[each for each in colors[:data.shape[0]]])
    plt.axis('equal')
    plt.show()

### Python 海龟绘图常用函数 #### 创建画布与初始化设置 为了使用 `turtle` 库中的功能,通常先要导入该模块并创建一个窗口实例。 ```python import turtle screen = turtle.Screen() pen = turtle.Turtle() # 初始化乌龟对象用于绘制 ``` #### 基本移动命令 - **前进**: 让海龟向前走指定的距离。 ```python pen.forward(100) # 向当前方向前进一步距离为100像素 ``` - **后退**: 让海龟向相反的方向行走给定单位长度。 ```python pen.backward(50) # 往回退步50个像素 ``` - **转向左转/右转**: 改变海龟面向的角度。 ```python pen.left(90) # 左转90度 pen.right(45) # 右转45度 ``` 这些基本操作可以组合起来完成更复杂的图案绘制[^1]。 #### 笔控制指令 除了上述运动外,还可以通过以下方法来管理线条属性: - **提起笔**:使之后的动作不会留下痕迹直到再次放下笔为止。 ```python pen.penup() # 提起笔不作画 ``` - **落下笔**:恢复正常的绘画状态。 ```python pen.pendown() # 落下笔回到正常画画模式 ``` - **改变颜色**:调整线的颜色以及填充色。 ```python pen.color('red') # 设置线条颜色为红色 pen.fillcolor('blue') # 设定填充区域颜色为蓝色 ``` 当涉及到封闭形状时,可以通过调用 `begin_fill()` 和 `end_fill()` 来实现彩色填充效果[^2]。 #### 绘制圆形和其他弧形路径 对于圆周或其他类型的曲线轨迹,有专门的方法支持这类几何图形的构建。 ```python pen.circle(radius=50, extent=None, steps=None) # radius参数定义半径大小;extent表示角度范围; # 如果steps被提供,则会近似成多边形而不是真正的圆弧 ``` 以上就是关于Python内置`turtle`库的一些基础介绍及其常见用途。此库非常适合初学者学习编程逻辑的同时享受视觉化的乐趣[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值