Python数据分析与展示:matplotlib绘图简单示例-7

图形的适用场景

关注分类变量各分类的比例,用饼图
关注变量的频率分布,用直方图
关注变量的变化趋势,用折线图
关注两个变量的相关,用散点图
展示一个变量的集中趋势和离散趋势,用箱图

导入库

# -*- coding: utf-8 -*-
# �64;File    : pylot_demo.py
# @Date    : 2018-05-14
import numpy as np
import matplotlib.pyplot as plt

饼图的绘制

def plot_pie1():
    labels = "Forgs", "Hogs", "Dogs", "Logs"
    sizes = [15, 30, 45, 10]
    explode = (0, 0.1, 0, 0)
    plt.pie(sizes, explode, labels, autopct='%1.1f%%', shadow=False, startangle=90)
    plt.savefig("pie1", dpi=600)
    plt.show()

Python数据分析与展示:matplotlib绘图简单示例-7

def plot_pie2():
    labels = "Forgs", "Hogs", "Dogs", "Logs"
    sizes = [15, 30, 45, 10]
    explode = (0, 0.1, 0, 0)
    plt.pie(sizes, explode, labels, autopct='%1.1f%%', shadow=False, startangle=90)
    plt.axis("equal")
    plt.savefig("pie2", dpi=600)
    plt.show()

Python数据分析与展示:matplotlib绘图简单示例-7

直方图的绘制

def plot_hist():
    np.random.seed(0)
    mu, sigma = 100, 20  # 均值和标准差
    a = np.random.normal(mu, sigma, size=100)
    # bins直方图的个数
    plt.hist(a, 20, normed=1, histtype="stepfilled", facecolor="b", alpha=0.75)
    plt.title("histogram")
    plt.savefig("hist", dpi=600)
    plt.show()

绘制极坐标图

def plot_polar():
    N = 20
    theta = np.linspace(0.0, 2*np.pi, N, endpoint=False)
    radii = 20 * np.random.randn(N)
    width = np.pi / 4 * np.random.randn(N)
    ax = plt.subplot(111, projection="polar")
    bars = ax.bar(theta, radii, width=width, bottom=0.0)
    for r, bar in zip(radii, bars):
        bar.set_facecolor(plt.cm.viridis(r/10.))
        bar.set_alpha(0.5)
    plt.savefig("polar", dpi=600)
    plt.show()

Python数据分析与展示:matplotlib绘图简单示例-7

绘制散点图

def plot_scatter():
    fig, ax = plt.subplots()
    ax.plot(10*np.random.randn(100), 10*np.random.randn(100), "o")
    ax.set_title("simple scatter")
    plt.savefig("scatter", dpi=600)
    plt.show()

Python数据分析与展示:matplotlib绘图简单示例-7