数据可视化库——Matplotlib、Seaborn、Pandas

文章目录

  • 数据可视化是数据分析的一个重要工具

第一部分 环境配置

1.1 要不要plt.show()

  • ipython中可用魔术方法 %matplotlib inline,一般在程序最开始就写这句,之后就不需要写 plt.show()
  • pycharm 中必须使用plt.show()
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")    # 设置样式

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)    # x和y数量必须对应
plt.ylabel("squares")    # y坐标轴名称
# plt.show()   

Text(0, 0.5, ‘squares’)
在这里插入图片描述

1.2 设置样式

import matplotlib.pyplot as plt

print(plt.style.available)    # 显示可用样式
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

with plt.style.context("seaborn-white"):    # 临时使用,仅在其下的代码块中用此样式
    plt.plot(x, y)
    plt.show()

plt.style.use("seaborn-whitegrid")    # 永久设置,如果后面不改的话,会一直延续这种样式

在这里插入图片描述

1.3 将图像保存为文件 plt.savefig

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10 ,100)
plt.plot(x, np.exp(x))
plt.savefig("my_figure.png")    # 注意后缀名要写

第二部分 Matplotlib库

2.1 折线图 plt.plot

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)    # 值取得多看起来会比较圆滑,本质上是折线图
plt.plot(x, np.sin(x))
plt.show()

在这里插入图片描述

绘制多条曲线
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.cos(x))
plt.plot(x, np.sin(x))
plt.show()

在这里插入图片描述

2.1.1 调整线条和标记点

调整线条颜色 color c
import matplotlib.pyplot as plt
import numpy as np

offsets = np.linspace(0, np.pi, 5)
colors = ["blue", "g", "r", "yellow", "pink"]    # 有些颜色可用简写
for offset, color in zip(offsets, colors):
    plt.plot(x, np.sin(x-offset), color=color)    # color可缩写为c
plt.show()

在这里插入图片描述

调整线条风格 linestyle ls
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 11)
offsets = list(range(8))
linestyles = ["solid", "dashed", "dashdot", "dotted", "-", "--", "-.", ":"]    # 后四个是前四个的简写
for offset, linestyle in zip(offsets, linestyles):
    plt.plot(x, x+offset, linestyle=linestyle)    # linestyle可简写为ls
plt.show()

在这里插入图片描述

调整线宽 linewidth lw
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
linewidths = (i*2 for i in range(1,5))
for offset, linewidth in zip(offsets, linewidths):
    plt.plot(x, x+offset, linewidth=linewidth)    # linewidth可简写为lw
plt.show()

在这里插入图片描述

调整数据点标记 marker
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
markers = ["*", "+", "o", "s"]
for offset, marker in zip(offsets, markers):
    plt.plot(x, x+offset, marker=marker)   
plt.show()

在这里插入图片描述

调整标记大小 markersize ms
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
markers = ["*", "+", "o", "s"]
for offset, marker in zip(offsets, markers):
    plt.plot(x, x+offset, marker=marker, markersize=10)      # markersize可简写为ms
plt.show()

在这里插入图片描述

颜色跟风格设置的简写
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_linestyles = ["g-", "b--", "k-.", "r:"]    # k是黑色
for offset, color_linestyle in zip(offsets, color_linestyles):
    plt.plot(x, x+offset, color_linestyle)
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_marker_linestyles = ["g*-", "b+--", "ko-.", "rs:"]
for offset, color_marker_linestyle in zip(offsets, color_marker_linestyles):
    plt.plot(x, x+offset, color_marker_linestyle)
plt.show()

在这里插入图片描述

2.1.2 调整坐标轴

plt.xlim 设置上下限
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.xlim(-1, 7)
plt.ylim(-1.5, 1.5)
plt.show()

在这里插入图片描述

plt.axis
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis([-2, 8, -2, 2])    # 设置上下限
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis("tight")    # 坐标轴适应数据量
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis("equal")    # x轴单位的实际长度和y轴单位的实际长度相同
plt.show()

在这里插入图片描述

?plt.axis 查看plt.axis的全部用法
import matplotlib.pyplot as plt
?plt.axis    # ipython中专用,命名空间搜索
对数坐标 plt.xscale
import matplotlib.pyplot as plt
import numpy as np

x = np.logspace(0, 5, 100)
plt.plot(x, np.log(x))
plt.xscale("log")
plt.show()

在这里插入图片描述

调整坐标轴刻度 plt.xticks
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.xticks(np.arange(0, 12, step=1))
plt.show()

在这里插入图片描述

调整坐标轴刻度字号 fontsize
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.xticks(np.arange(0, 12, step=1), fontsize=15)
plt.yticks(np.arange(0, 110, step=10))
plt.show()

在这里插入图片描述

调整刻度样式 plt.tick_params
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.tick_params(axis="both", labelsize=15)
plt.show()

在这里插入图片描述

2.1.3 设置图形标签 plt.title plt.xlabel

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.title("A Sine Curve", fontsize=20)
plt.xlabel("x", fontsize=15)
plt.ylabel("sin(x)", fontsize=15)
plt.show()

在这里插入图片描述

2.1.4 设置图例 plt.legend

默认
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-", label="Sin")
plt.plot(x, np.cos(x), "r--", label="Cos")
plt.legend()
plt.show()

在这里插入图片描述

修饰图例
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-", label="Sin")
plt.plot(x, np.cos(x), "r--", label="Cos")
plt.ylim(-1.5, 2)
plt.legend(loc="upper center", frameon=True, fontsize=15)    # loc有9种和best,frameon显示底框
plt.show()

在这里插入图片描述

2.1.5 添加文字和箭头

添加文字 plt.text
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-")
plt.text(3.5, 0.5, "y=sin(x)", fontsize=15)
plt.show()

在这里插入图片描述

添加箭头 plt.annotate
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-")
plt.annotate('local min', xy=(1.5*np.pi, -1), xytext=(4.5, 0),
             arrowprops=dict(facecolor='black', shrink=0.1),
             )    # xy箭头指向的位置,xytext文字位置,shrink箭头长度
plt.show()

在这里插入图片描述

2.2 散点图 plt.scatter

2.2.1 简单散点图

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 20)
plt.scatter(x, np.sin(x), marker="o", s=30, c="r")    # s 大小  c 颜色
plt.show()

在这里插入图片描述

2.2.2 颜色配置 cmap

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = x**2
plt.scatter(x, y, c=y, cmap="inferno")    # cmap 颜色映射
plt.colorbar()    # 显示映射条
plt.show()

在这里插入图片描述

颜色配置参考官方文档

https://matplotlib.org/examples/color/colormaps_reference.html

2.2.3 根据数据控制点的大小

import matplotlib.pyplot as plt
import numpy as np

x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis")    # s数据点大小,c和s要跟数据点数量对应
plt.show()

在这里插入图片描述

2.2.4 透明度 alpha 0-1

import matplotlib.pyplot as plt
import numpy as np

x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis", alpha=0.3)
plt.colorbar()
plt.show()

在这里插入图片描述

【例】随机漫步

import matplotlib.pyplot as plt
import numpy as np
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 = RandomWalk(10000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.figure(figsize=(12, 6))    # 画布大小,宽12,高6     
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap="inferno", s=1)
plt.colorbar()
plt.scatter(0, 0, c="green", s=100)    #起始和结束点设置
plt.scatter(rw.x_values[-1], rw.y_values[-1], c="red", s=100)
​
plt.xticks([])    # 隐藏坐标轴
plt.yticks([])
plt.show()

在这里插入图片描述

2.3 柱形图 plt.bar

2.3.1 简单柱形图

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 6)
plt.bar(x, 2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')    # align柱子放在数字的中间,edgecolor柱子边缘颜色
plt.tick_params(axis="both", labelsize=13)
plt.show()

在这里插入图片描述

设置坐标轴显示内容
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 6)
plt.bar(x, 2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.xticks(x, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.tick_params(axis="both", labelsize=13) 
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = ('G1', 'G2', 'G3', 'G4', 'G5')
y = 2 * np.arange(1, 6)
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.tick_params(axis="both", labelsize=13) 
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = ["G"+str(i) for i in range(5)]
y = 1/(1+np.exp(-np.arange(5)))
​
colors = ['red', 'yellow', 'blue', 'green', 'gray']
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color=colors)
plt.tick_params(axis="both", labelsize=13)
plt.show()

在这里插入图片描述

2.3.2 累加柱形图 bottom

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y1 = np.random.randint(20, 30, size=5)
y2 = np.random.randint(20, 30, size=5)
plt.bar(x, y1, width=0.5, label="man")
plt.bar(x, y2, width=0.5, bottom=y1, label="women")
plt.legend()
plt.show()

在这里插入图片描述

2.3.3 并列柱形图

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(15)
y1 = x+1
y2 = y1+np.random.random(15)
plt.bar(x, y1, width=0.3, label="man")
plt.bar(x+0.3, y2, width=0.3, label="women")
plt.legend()
plt.show()

在这里插入图片描述

2.3.4 横向柱形图 plt.barh

import matplotlib.pyplot as plt
import numpy as np

x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 * np.arange(1, 6)
plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue", edgecolor="red")    # 注意柱子宽度用height
plt.tick_params(axis="both", labelsize=13)
plt.show()

在这里插入图片描述

2.4 多子图 plt.subplot

2.4.1 简单多子图

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
​
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
​
plt.subplot(211)    # 前两个数字代表两行一列,后面的1代表第一个
plt.plot(t1, f(t1), "bo-", markerfacecolor="r", markersize=5)
plt.title("A tale of 2 subplots")
plt.ylabel("Damped oscillation")
​
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), "r--")
plt.xlabel("time (s)")
plt.ylabel("Undamped")
plt.show()

在这里插入图片描述

2.4.2 多行多列子图

import matplotlib.pyplot as plt
import numpy as np

x = np.random.random(10)
y = np.random.random(10)
​
plt.subplots_adjust(hspace=0.5, wspace=0.3)    # 定义横向纵向的间隔
​
plt.subplot(321)
plt.scatter(x, y, s=80, c="b", marker=">")
​
plt.subplot(322)
plt.scatter(x, y, s=80, c="g", marker="*")
​
plt.subplot(323)
plt.scatter(x, y, s=80, c="r", marker="s")
​
plt.subplot(324)
plt.scatter(x, y, s=80, c="c", marker="p")
​
plt.subplot(325)
plt.scatter(x, y, s=80, c="m", marker="+")
​
plt.subplot(326)
plt.scatter(x, y, s=80, c="y", marker="H")
plt.show()

在这里插入图片描述

2.4.3 不规则多子图 plt.GridSpec

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    return np.exp(-x) * np.cos(2*np.pi*x)
​
​
x = np.arange(0.0, 3.0, 0.01)
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)    # 2行3列的网格
​
plt.subplot(grid[0, 0])
plt.plot(x, f(x))
​
plt.subplot(grid[0, 1:])
plt.plot(x, f(x), "r--", lw=2)
​
plt.subplot(grid[1, :])
plt.plot(x, f(x), "g-.", lw=3)
plt.show()

在这里插入图片描述

2.5 直方图 plt.hist

2.5.1 普通频次直方图

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)    # 均值100,标准差15
​
plt.hist(x, bins=50, facecolor='g', alpha=0.75)    # 分成50个区间
plt.show()

在这里插入图片描述

2.5.2 概率密度 density=True

  • 频次转换成频率,除以区间长度,可以转化成概率密度图
import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
​
plt.hist(x, 50, density=True, color="r")
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.show()

在这里插入图片描述

histtype='step’获得边缘图
import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
​
plt.hist(x, bins=50, density=True, color="r", histtype='step') 
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.show()

在这里插入图片描述

获得真正的高斯分布
import matplotlib.pyplot as plt
import numpy as np

from scipy.stats import norm
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
​
_, bins, __ = plt.hist(x, 50, density=True)    # 获得区间
y = norm.pdf(bins, mu, sigma)    # 计算符合分布的概率密度
plt.plot(bins, y, 'r--', lw=3)  
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.show()

在这里插入图片描述

  • 蓝色是实验获得的,红色是标准的

2.5.3 累计概率分布 cumulative=True

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
​
plt.hist(x, 50, density=True, cumulative=True, color="r")
plt.xlabel('Smarts')
plt.ylabel('Cum_Probability')
plt.title('Histogram of IQ')
plt.text(60, 0.8, r'$\mu=100,\ \sigma=15$')
plt.xlim(50, 165)
plt.ylim(0, 1.1)
plt.show()

在这里插入图片描述

【例】模拟投两个骰子

import matplotlib.pyplot as plt
import numpy as np


class Die():
    "模拟一个骰子的类"
    
    def __init__(self, num_sides=6):
        self.num_sides = num_sides
    
    def roll(self):
        return np.random.randint(1, self.num_sides+1)


# 重复投一个骰子
die = Die()
results = []
for i in range(60000):
    result = die.roll()
    results.append(result)
    
plt.hist(results, bins=6, range=(0.75, 6.75), align="mid", width=0.5)    # range 从(0.75, 6.75)划分6个区间
# center?
plt.xlim(0 ,7)
plt.show()

# 重复投两个骰子
die1 = Die()
die2 = Die()
results = []
for i in range(60000):
    result = die1.roll()+die2.roll()
    results.append(result)
    
plt.hist(results, bins=11, range=(1.75, 12.75), align="mid", width=0.5)
plt.xlim(1 ,13)
plt.xticks(np.arange(1, 14))
plt.show()

在这里插入图片描述
在这里插入图片描述

2.6 误差图 plt.errorbar

2.6.1 基本误差图

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10 ,50)
dy = 0.5
y = np.sin(x) + dy*np.random.randn(50)
​
plt.errorbar(x, y , yerr=dy, fmt="+b")    # fmt设置颜色形状
plt.show()

在这里插入图片描述

2.6.2 柱形图误差图

import matplotlib.pyplot as plt
import numpy as np

menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = ['G1', 'G2', 'G3', 'G4', 'G5'] 
width = 0.35       
​
p1 = plt.bar(ind, menMeans, width=width, label="Men", yerr=menStd)
p2 = plt.bar(ind, womenMeans, width=width, bottom=menMeans, label="Women", yerr=womenStd)
​
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.yticks(np.arange(0, 81, 10))
plt.legend()
plt.show()

在这里插入图片描述

2.7 面向对象的风格简介

  • 把每个图,每个轴,看成一个对象,可以编辑每个对象,增加绘图灵活性

2.7.1 普通图

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 10)
y = x ** 2
​
fig = plt.figure(figsize=(8,4), dpi=80)        # 图像 figsize画布大小,dpi像素
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])      # 轴 left, bottom, width, height (range 0 to 1)
​
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
plt.show()

在这里插入图片描述

2.7.2 画中画

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 10)
y = x ** 2
​
fig = plt.figure()
​
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 
ax2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) 
​
ax1.plot(x, y, 'r')
​
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
​
ax2.plot(y, x, 'g')
ax2.set_xlabel('y')
ax2.set_ylabel('x')
ax2.set_title('insert title')
plt.show()

在这里插入图片描述

2.7.3 多子图

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
​
​
t1 = np.arange(0.0, 3.0, 0.01)
​
fig= plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
​
ax1 = plt.subplot(2, 2, 1)
ax1.plot(t1, f(t1))
ax1.set_title("Upper left")
​
ax2 = plt.subplot(2, 2, 2)
ax2.plot(t1, f(t1))
ax2.set_title("Upper right")
​
ax3 = plt.subplot(2, 1, 2)    # 注意这里
ax3.plot(t1, f(t1))
ax3.set_title("Lower")
plt.show()

在这里插入图片描述

2.8 三维图形简介

2.8.1 三维数据点与线

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
​
ax = plt.axes(projection="3d")
# 绘制螺旋线
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline ,zline)#绘制点
zdata = 15*np.random.random(100)
xdata = np.sin(zdata)
ydata = np.cos(zdata)
ax.scatter3D(xdata, ydata ,zdata, c=zdata, cmap="spring")
plt.show()

在这里插入图片描述

2.8.2 三维数据曲面图 plot_surface

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d

def f(x, y):
    return np.sin(np.sqrt(x**2 + y**2))
​
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)    # 网格化
Z = f(X, Y)
​
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
​
t = np.linspace(0, 2*np.pi, 1000)
X = np.sin(t)
Y = np.cos(t)
Z = np.arange(t.size)[:, np.newaxis]
​
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
plt.show()

在这里插入图片描述

第三部分 Seaborn库-文艺青年的最爱

3.1 Seaborn 与 Matplotlib

  • Seaborn 是一个基于 matplotlib 且数据结构与 pandas 统一的统计图制作库
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 500)    # 500个数据
y = np.cumsum(np.random.randn(500, 6), axis=0)    # 500行6列

with plt.style.context("classic"):
    plt.plot(x, y)    # 自动对齐,绘制出6条曲线
    plt.legend("ABCDEF", ncol=2, loc="upper left")   # ncol图例分几列
plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
​
x = np.linspace(0, 10, 500)
y = np.cumsum(np.random.randn(500, 6), axis=0)
sns.set()    # 改变了绘制格式,变成seaborn风格
plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.legend("ABCDEF", ncol=2, loc="upper left")
plt.show()

在这里插入图片描述

3.2 柱形图的对比 sns.barplot

import numpy as np
import matplotlib.pyplot as plt

x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 * np.arange(1, 6)
​
plt.figure(figsize=(8, 4))
plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue")
plt.tick_params(axis="both", labelsize=13)
plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.set()
plt.figure(figsize=(8, 4))
x = ['G5', 'G4', 'G3', 'G2', 'G1']
y = 2 * np.arange(5, 0, -1)
sns.barplot(y, x, linewidth=5)
plt.show()

在这里插入图片描述

sns.barplot? 查看其它用法
import seaborn as sns
sns.barplot?

3.3 以鸢尾花数据集为例 sns.pairplot

  • 查看前4种数据的相关性
import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
print(iris.head())
   sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
3           4.6          3.1           1.5          0.2  setosa
4           5.0          3.6           1.4          0.2  setosa
sns.set()
sns.pairplot(data=iris, hue="species")
plt.show()

在这里插入图片描述

  • 可以看出花瓣长度与花瓣宽度的线性关系很明显
    花萼长度与花萼宽度线性很差
  • 对角线上是对应维度下三种鸢尾花的边缘概率分布,分得比较开的说明数据比较容易分离
解决sns.pairplot()中文问题
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14)
sns.set(font=myfont.get_name())

第四部分 Pandas 中的绘图函数概览

4.1 线形图 df.plot()

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

sns.set()
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
                  columns=list("ABCD"),
                  index=np.arange(1000))
print(df.head())
          A         B         C         D
0  0.139109  0.128463 -0.084513  0.025072
1  0.085295  0.061121  1.157259  0.896488
2  2.015443  2.157705  0.607950  2.153834
3  0.004897  1.885500  0.199746  2.315296
4 -0.828913  1.183246  2.914528  1.882888
df.plot()
plt.show()

在这里插入图片描述

df.plot的其它用法 df.plot?

import pandas as pd

df = pd.DataFrame()
df.plot?

4.2 柱形图 df.plot.bar()

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

sns.set()

df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
print(df2)
          a         b         c         d
0  0.192956  0.043906  0.485144  0.795992
1  0.584856  0.473277  0.703299  0.189399
2  0.860249  0.857595  0.453057  0.254671
3  0.334403  0.761708  0.343463  0.188714
4  0.713408  0.380034  0.136699  0.045663
5  0.268257  0.701495  0.087406  0.941839
6  0.373573  0.483803  0.537277  0.847954
7  0.324497  0.534841  0.786176  0.057222
8  0.527766  0.129430  0.745205  0.852565
9  0.410403  0.356154  0.050476  0.562084

多组数据竖图

df2.plot.bar()
plt.show()

在这里插入图片描述

多组数据累加竖图 stacked=True

df2.plot.bar(stacked=True)
plt.show()

在这里插入图片描述

多组数据累加横图 df.plot.barh

df2.plot.barh(stacked=True)
plt.show()

在这里插入图片描述

4.3 直方图和密度图

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

sns.set()

df4 = pd.DataFrame({"A": np.random.randn(1000) - 3, "B": np.random.randn(1000),
                     "C": np.random.randn(1000) + 3})
print(df4.head())
          A         B         C
0 -2.974090  0.811919  1.454981
1 -3.918316  1.246171  3.292422
2 -3.584788  1.339561  4.249672
3 -3.927277  0.368552  3.799760
4 -3.020831  1.555329  3.881246

普通直方图 df.plot.hist

df4.plot.hist(bins=50)
plt.show()

在这里插入图片描述

累加直方图 cumulative=True

df4['A'].plot.hist(cumulative=True)
plt.show()

在这里插入图片描述

概率密度图 kind=“kde”

df4['A'].plot(kind="kde")
plt.show()

在这里插入图片描述

差分 累加图还原 df.diff().hist

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

sns.set()

df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
                  columns=list("ABCD"),
                  index=np.arange(1000))
print(df.head())
          A         B         C         D
0  0.862603  0.716191 -0.962349  0.571769
1 -0.011500  0.771621 -0.545608  1.226492
2  0.475496  0.412311 -1.535971  2.822753
3  0.809000  0.751493 -1.513082  2.713575
4  1.081569  0.719442 -3.359304  3.251815
df.diff().hist(bins=50, color="r")
plt.show()

在这里插入图片描述

df.hist? 查看其它
import pandas as pd
df = pd.DataFrame()
df.hist?

4.4 散点图 以加州房价数据集为例

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

housing = pd.read_csv("housing.csv")
housing.head()
   longitude  latitude  housing_median_age  total_rooms  total_bedrooms  population  households  median_income  median_house_value ocean_proximity  
0    -122.23     37.88                41.0        880.0           129.0       322.0       126.0         8.3252            452600.0        NEAR BAY     
1    -122.22     37.86                21.0       7099.0          1106.0      2401.0      1138.0         8.3014            358500.0        NEAR BAY     
2    -122.24     37.85                52.0       1467.0           190.0       496.0       177.0         7.2574            352100.0        NEAR BAY     
3    -122.25     37.85                52.0       1274.0           235.0       558.0       219.0         5.6431            341300.0        NEAR BAY     
4    -122.25     37.85                52.0       1627.0           280.0       565.0       259.0         3.8462            342200.0        NEAR BAY     
"""基于地理数据的人口、房价可视化"""
# 圆的半径大小代表每个区域人口数量(s),颜色代表价格(c),用预定义的jet表进行可视化
# x经度,y纬度
#有圈的地方代表有城市,圈越大,人口越多,颜色偏蓝说明房价低,偏红说明房价高
with sns.axes_style("white"):
    housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.6,
                 s=housing["population"]/100, label="population",
                 c="median_house_value", cmap="jet", colorbar=True, figsize=(12, 8))
plt.legend()
plt.axis([-125, -113.5, 32, 43])
plt.show()

在这里插入图片描述

  • 取平均工资和平均房价
housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.8)
plt.show()

在这里插入图片描述

4.5 多子图 subplots=True

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

sns.set()

df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
                  columns=list("ABCD"),
                  index=np.arange(1000))
print(df.head())
          A         B         C         D
0 -0.841199  0.021080  0.679416 -1.115123
1 -1.352381  0.493308  1.756238 -1.723150
2 -2.068088 -1.531768  0.801734 -1.277159
3 -0.445886 -3.386234  0.727494 -0.862176
4  1.311162 -5.831062  1.646270  0.099221

默认情形

df.plot(subplots=True, figsize=(6, 16))
plt.show()

在这里插入图片描述

设定图形安排

df.plot(subplots=True, layout=(2, 2), figsize=(16, 6), sharex=False)
plt.show()

在这里插入图片描述

其他内容请参考Pandas中文文档

https://www.pypandas.cn/docs/user_guide/visualization.html#plot-formatting

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值