Python基础(十二) 还不会python绘图?两万字博文教你Matplotlib库(超详细总结)_python绘图不从头开始(2)

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis(“equal”)



(0.0, 7.0, -1.0, 1.0)


![png](https://img-blog.csdnimg.cn/img_convert/7056b88cbabad82d85dff6a135cb5c1e.png)



?plt.axis # 可以查询其中的功能



Object plt.axis # 可以查询其中的功能 not found.


* 对数坐标



x = np.logspace(0, 5, 100)
plt.plot(x, np.log(x))
plt.xscale(“log”)


![png](https://img-blog.csdnimg.cn/img_convert/867c1b161b4bac4fce2f80000817a00f.png)


* 调整坐标轴刻度


plt.xticks(np.arange(0, 12, step=1))



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



([<matplotlib.axis.XTick at 0x18846412828>,
<matplotlib.axis.XTick at 0x18847665898>,
<matplotlib.axis.XTick at 0x18847665630>,
<matplotlib.axis.XTick at 0x18847498978>,
<matplotlib.axis.XTick at 0x18847498390>,
<matplotlib.axis.XTick at 0x18847497d68>,
<matplotlib.axis.XTick at 0x18847497748>,
<matplotlib.axis.XTick at 0x18847497438>,
<matplotlib.axis.XTick at 0x1884745f438>,
<matplotlib.axis.XTick at 0x1884745fd68>,
<matplotlib.axis.XTick at 0x18845fcf4a8>,
<matplotlib.axis.XTick at 0x18845fcf320>],
<a list of 12 Text xticklabel objects>)


![png](https://img-blog.csdnimg.cn/img_convert/dac0a3ce6c785fcffc864d735b838cd8.png)



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))



([<matplotlib.axis.YTick at 0x188474f0860>,
<matplotlib.axis.YTick at 0x188474f0518>,
<matplotlib.axis.YTick at 0x18847505a58>,
<matplotlib.axis.YTick at 0x188460caac8>,
<matplotlib.axis.YTick at 0x1884615c940>,
<matplotlib.axis.YTick at 0x1884615cdd8>,
<matplotlib.axis.YTick at 0x1884615c470>,
<matplotlib.axis.YTick at 0x1884620c390>,
<matplotlib.axis.YTick at 0x1884611f898>,
<matplotlib.axis.YTick at 0x188461197f0>,
<matplotlib.axis.YTick at 0x18846083f98>],
<a list of 11 Text yticklabel objects>)


![png](https://img-blog.csdnimg.cn/img_convert/aeb86787ce668868ce8e27e23c3030cc.png)


* 调整刻度样式


plt.tick\_params(axis=“both”, labelsize=15)



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


![png](https://img-blog.csdnimg.cn/img_convert/027992858b5b2ad8ae341b4511645f9e.png)


##### 【3】设置图形标签



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)



Text(0, 0.5, ‘sin(x)’)


![png](https://img-blog.csdnimg.cn/img_convert/47dfc38d5a4a594f2cecfdca4c911ca2.png)


【4】设置图例


* 默认



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()



<matplotlib.legend.Legend at 0x1884749f908>


![png](https://img-blog.csdnimg.cn/img_convert/0b20990bde0b3461c78c7e1f0a8f73eb.png)


* 修饰图例



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) # frameon=True增加图例的边框



<matplotlib.legend.Legend at 0x19126b53b80>


![png](https://img-blog.csdnimg.cn/img_convert/1dd8b445b377535f1d8ac231feb53efe.png)


【5】添加文字和箭头


* 添加文字



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) # 前两个为文字的坐标,后面是内容和字号



Text(3.5, 0.5, ‘y=sin(x)’)


![png](https://img-blog.csdnimg.cn/img_convert/1cfcbedaa405922de9518183c92e6586.png)


* 添加箭头



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),
)



Text(4.5, 0, ‘local min’)


![png](https://img-blog.csdnimg.cn/img_convert/2117bd865adbd173079f4ce9c1606fa3.png)


#### 13.1.2 散点图


【1】简单散点图



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



<matplotlib.collections.PathCollection at 0x188461eb4a8>


![png](https://img-blog.csdnimg.cn/img_convert/862d6240050eabff03589230b0e5efb4.png)


【2】颜色配置



x = np.linspace(0, 10, 100)
y = x**2
plt.scatter(x, y, c=y, cmap=“inferno”) # 让c随着y的值变化在cmap中进行映射
plt.colorbar() # 输出颜色条



<matplotlib.colorbar.Colorbar at 0x18848d392e8>


![png](https://img-blog.csdnimg.cn/img_convert/43f843a14c093b0776e2e7c01524f75f.png)


颜色配置参考官方文档


https://matplotlib.org/examples/color/colormaps\_reference.html


【3】根据数据控制点的大小



x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap=“viridis”)



<matplotlib.collections.PathCollection at 0x18847b48748>


![png](https://img-blog.csdnimg.cn/img_convert/e265d0dbc374f4c4fcd3fae7f3d6c7ac.png)


【4】透明度



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()



<matplotlib.colorbar.Colorbar at 0x18848f2be10>


![png](https://img-blog.csdnimg.cn/img_convert/5352fafd67dd153db16c1a46806ab21a.png)


【例】随机漫步



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 or 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)) # 设置画布大小
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([])



([], <a list of 0 Text yticklabel objects>)


​  
 ![png](https://img-blog.csdnimg.cn/img_convert/8c3fb73ddf4811de03f76cf881ca30e2.png)  
 ​


#### 13.1.3 柱形图


【1】简单柱形图



x = np.arange(1, 6)
plt.bar(x, 2*x, align=“center”, width=0.5, alpha=0.5, color=‘yellow’, edgecolor=‘red’)
plt.tick_params(axis=“both”, labelsize=13)


![png](https://img-blog.csdnimg.cn/img_convert/6d7944045dc27af6d716c32c9e2fad01.png)



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)


![png](https://img-blog.csdnimg.cn/img_convert/a385c1c016e0f5cf18721f5d4737e685.png)



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)


![png](https://img-blog.csdnimg.cn/img_convert/229e9bf91e25baa421945a98ac9a7341.png)



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)


![png](https://img-blog.csdnimg.cn/img_convert/9e09f0b7b0213d46ab7c7c7f8c0d7b8a.png)


【2】累加柱形图



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()



<matplotlib.legend.Legend at 0x2052db25cc0>


![png](https://img-blog.csdnimg.cn/img_convert/3cfe9262979b69184c1e120ad5a878cf.png)


【3】并列柱形图



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()



<matplotlib.legend.Legend at 0x2052daf35f8>


![png](https://img-blog.csdnimg.cn/img_convert/5ac8cb26ffe288ec3626071fc142c09e.png)


【4】横向柱形图barh



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”) # 注意这里将bar改为barh,宽度用height设置
plt.tick_params(axis=“both”, labelsize=13)


![png](https://img-blog.csdnimg.cn/img_convert/b62a3527f9d496bfb105755a59f834e8.png)


#### 13.1.4 多子图


【1】简单多子图



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)
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”)



Text(0, 0.5, ‘Undamped’)


![png](https://img-blog.csdnimg.cn/img_convert/bbe7f59a4275a00bccdfb252dba0124c.png)


【2】多行多列子图



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”)



<matplotlib.collections.PathCollection at 0x2052d9f63c8>


![png](https://img-blog.csdnimg.cn/img_convert/905ef6951526b47771ab0e5753b214a1.png)


【3】不规则多子图



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) # 两行三列的网格

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)



[<matplotlib.lines.Line2D at 0x2052d6fae80>]


![png](https://img-blog.csdnimg.cn/img_convert/3efcb9681d4e47a12027bd262f8b132e.png)


#### 13.1.5 直方图


【1】普通频次直方图



mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

plt.hist(x, bins=50, facecolor=‘g’, alpha=0.75)



(array([ 1., 0., 0., 5., 3., 5., 1., 10., 15., 19., 37.,
55., 81., 94., 125., 164., 216., 258., 320., 342., 401., 474.,
483., 590., 553., 551., 611., 567., 515., 558., 470., 457., 402.,
347., 261., 227., 206., 153., 128., 93., 79., 41., 22., 17.,
21., 9., 2., 8., 1., 2.]),
array([ 40.58148736, 42.82962161, 45.07775586, 47.32589011,
49.57402436, 51.82215862, 54.07029287, 56.31842712,
58.56656137, 60.81469562, 63.06282988, 65.31096413,
67.55909838, 69.80723263, 72.05536689, 74.30350114,
76.55163539, 78.79976964, 81.04790389, 83.29603815,
85.5441724 , 87.79230665, 90.0404409 , 92.28857515,
94.53670941, 96.78484366, 99.03297791, 101.28111216,
103.52924641, 105.77738067, 108.02551492, 110.27364917,
112.52178342, 114.76991767, 117.01805193, 119.26618618,
121.51432043, 123.76245468, 126.01058893, 128.25872319,
130.50685744, 132.75499169, 135.00312594, 137.25126019,
139.49939445, 141.7475287 , 143.99566295, 146.2437972 ,
148.49193145, 150.74006571, 152.98819996]),
<a list of 50 Patch objects>)


![png](https://img-blog.csdnimg.cn/img_convert/a413fa8109f4acc6bd6d4420934f3826.png)


【2】概率密度



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’ μ = 100 ,   σ = 15 \mu=100,\ \sigma=15 μ=100, σ=15’)
plt.xlim(40, 160)
plt.ylim(0, 0.03)



(0, 0.03)


![png](https://img-blog.csdnimg.cn/img_convert/5ae5627fded3597c73bc454485072089.png)



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’ μ = 100 ,   σ = 15 \mu=100,\ \sigma=15 μ=100, σ=15’)
plt.xlim(40, 160)
plt.ylim(0, 0.03)



(0, 0.03)


![png](https://img-blog.csdnimg.cn/img_convert/0c403341394e07e9c6d0de5a17700902.png)



from scipy.stats import norm
mu, sigma = 100, 15 # 想获得真正高斯分布的概率密度图
x = mu + sigma * np.random.randn(10000)

先获得bins,即分配的区间

_, bins, __ = plt.hist(x, 50, density=True)
y = norm.pdf(bins, mu, sigma) # 通过norm模块计算符合的概率密度
plt.plot(bins, y, ‘r–’, lw=3)
plt.xlabel(‘Smarts’)
plt.ylabel(‘Probability’)
plt.title(‘Histogram of IQ’)
plt.text(60, .025, r’ μ = 100 ,   σ = 15 \mu=100,\ \sigma=15 μ=100, σ=15’)
plt.xlim(40, 160)
plt.ylim(0, 0.03)



(0, 0.03)


![png](https://img-blog.csdnimg.cn/img_convert/d42ee9328529880b7ed37553d5c030b1.png)


【3】累计概率分布



mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

plt.hist(x, 50, density=True, cumulative=True, color=“r”) # 将累计cumulative设置为true即可
plt.xlabel(‘Smarts’)
plt.ylabel(‘Cum_Probability’)
plt.title(‘Histogram of IQ’)
plt.text(60, 0.8, r’ μ = 100 ,   σ = 15 \mu=100,\ \sigma=15 μ=100, σ=15’)
plt.xlim(50, 165)
plt.ylim(0, 1.1)



(0, 1.1)


![png](https://img-blog.csdnimg.cn/img_convert/f372ffdb0f5bd1a9f0ed242d5eeee229.png)


【例】模拟投两个骰子



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)
plt.xlim(0 ,7)



(0, 7)


![png](https://img-blog.csdnimg.cn/img_convert/3cab569cd2500719bcb156d27ddde1f4.png)


* 重复投两个骰子



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))



([<matplotlib.axis.XTick at 0x2052fae23c8>,
<matplotlib.axis.XTick at 0x2052ff1fa20>,
<matplotlib.axis.XTick at 0x2052fb493c8>,
<matplotlib.axis.XTick at 0x2052e9b5a20>,
<matplotlib.axis.XTick at 0x2052e9b5e80>,
<matplotlib.axis.XTick at 0x2052e9b5978>,
<matplotlib.axis.XTick at 0x2052e9cc668>,
<matplotlib.axis.XTick at 0x2052e9ccba8>,
<matplotlib.axis.XTick at 0x2052e9ccdd8>,
<matplotlib.axis.XTick at 0x2052fac5668>,
<matplotlib.axis.XTick at 0x2052fac5ba8>,
<matplotlib.axis.XTick at 0x2052fac5dd8>,
<matplotlib.axis.XTick at 0x2052fad9668>],
<a list of 13 Text xticklabel objects>)


![png](https://img-blog.csdnimg.cn/img_convert/708c22f25b2ef94e08a78f6f3b84fc59.png)


#### 13.1.6 误差图


【1】基本误差图



x = np.linspace(0, 10 ,50)
dy = 0.5 # 每个点的y值误差设置为0.5
y = np.sin(x) + dy*np.random.randn(50)

plt.errorbar(x, y , yerr=dy, fmt=“+b”)



<ErrorbarContainer object of 3 artists>


![png](https://img-blog.csdnimg.cn/img_convert/dc9bc39f8bf560d4f1f25747239433d4.png)


【2】柱形图误差图



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=“Men”, yerr=womenStd)

plt.ylabel(‘Scores’)
plt.title(‘Scores by group and gender’)
plt.yticks(np.arange(0, 81, 10))
plt.legend()



<matplotlib.legend.Legend at 0x20531035630>


![png](https://img-blog.csdnimg.cn/img_convert/12e1f64f3d28f233dcc463ed97b91b68.png)


#### 13.1.7 面向对象的风格简介


【例1】 普通图



x = np.linspace(0, 5, 10)
y = x ** 2

fig = plt.figure(figsize=(8,4), dpi=80) # 图像
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’)



Text(0.5, 1.0, ‘title’)


![png](https://img-blog.csdnimg.cn/img_convert/7fb8a6bfde20c6293897d70ad5312f76.png)


【2】画中画



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’)



Text(0.5, 1.0, ‘insert title’)


![png](https://img-blog.csdnimg.cn/img_convert/bb640e37289a7b4a1d4be1f70128edc6.png)


【3】 多子图



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”)



Text(0.5, 1.0, ‘Lower’)


![png](https://img-blog.csdnimg.cn/img_convert/1b17b188157a57b6d2a4ff6dcd42a1bb.png)


#### 13.1.8 三维图形简介


【1】三维数据点与线



from mpl_toolkits import mplot3d # 注意要导入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”) # 点的绘制



<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x2052fd1e5f8>


![png](https://img-blog.csdnimg.cn/img_convert/046a043330c6aecf51872d80abb8ca16.png)


【2】三维数据曲面图



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”) # 设置颜色映射



<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x20531baa5c0>


![png](https://img-blog.csdnimg.cn/img_convert/1b2f0ef255e6fe3d1a74000bdf6807ce.png)



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”)



<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x1c540cf1cc0>


![png](https://img-blog.csdnimg.cn/img_convert/687057a728556473b10565dc5c621f79.png)


### 13.2 Seaborn库-文艺青年的最爱


【1】Seaborn 与 Matplotlib


Seaborn 是一个基于 matplotlib 且数据结构与 pandas 统一的统计图制作库



x = np.linspace(0, 10, 500)
y = np.cumsum(np.random.randn(500, 6), axis=0)

with plt.style.context(“classic”):
plt.plot(x, y)
plt.legend(“ABCDEF”, ncol=2, loc=“upper left”)


![png](https://img-blog.csdnimg.cn/img_convert/608edb3a59eaf68d424836a148468aad.png)



import seaborn as sns

x = np.linspace(0, 10, 500)
y = np.cumsum(np.random.randn(500, 6), axis=0)
sns.set()# 改变了格式
plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.legend(“ABCDEF”, ncol=2, loc=“upper left”)



<matplotlib.legend.Legend at 0x20533d825f8>


![png](https://img-blog.csdnimg.cn/img_convert/da1a21f99b02c377a7d8ee70d9d7bce0.png)


【2】柱形图的对比



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)


![png](https://img-blog.csdnimg.cn/img_convert/45d6f1480c5c1807a373f878fffe16d3.png)



import seaborn as sns

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



<matplotlib.axes._subplots.AxesSubplot at 0x20533e92048>


![png](https://img-blog.csdnimg.cn/img_convert/9c4ec6b2d256f2c6cb6ec5cf930eab44.png)



sns.barplot?


【3】以鸢尾花数据集为例



iris = sns.load_dataset(“iris”)



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.pairplot(data=iris, hue=“species”)




![img](https://img-blog.csdnimg.cn/img_convert/5ab0231f7230b3d038ccdc28172cf700.png)
![img](https://img-blog.csdnimg.cn/img_convert/88b8cc7dcb09b686eba1cf72c7483e4b.png)
![img](https://img-blog.csdnimg.cn/img_convert/2e2a313368cbc8f18ee4dc02fd19265e.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**

fffe16d3.png)



import seaborn as sns

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



<matplotlib.axes._subplots.AxesSubplot at 0x20533e92048>


![png](https://img-blog.csdnimg.cn/img_convert/9c4ec6b2d256f2c6cb6ec5cf930eab44.png)



sns.barplot?


【3】以鸢尾花数据集为例



iris = sns.load_dataset(“iris”)



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.pairplot(data=iris, hue=“species”)




[外链图片转存中...(img-4XxSBVKg-1715529351633)]
[外链图片转存中...(img-fZ2MtGSb-1715529351633)]
[外链图片转存中...(img-W0bZpWyn-1715529351634)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**

  • 15
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值