50题matplotlib从入门到精通-手把手使用Anaconda实践

最近看到文章《50题matplotlib从入门到精通》觉得很有意义,实践如下:
一,编程环境
这里我使用Anaconda3,需要软件的从百度云盘下载。
下载地址:https://pan.baidu.com/s/11WrltUbAV-Z9SvprY91Pxw 提取码: nafe
安装好后,我使用jupyter notebook进行实践。
这里介绍一个较简单的我常用的运行方法:

  • 找到开始菜单中已安装好的Anaconda目录,找到Anaconda Prompt并运行

  • 如我在D盘的pythontest文件中运行和保存文件,只需要输入D:盘符,cd转入pythontest文件夹,运行jupyter notebook,如图(注意运行期间,该窗口不可关闭):
    在这里插入图片描述

  • 即可在网页中打开jupyter notebook。通过右侧的new下拉按钮,选择Python3,即可创建一个python文件"Untitled.ipynb"如图:
    在这里插入图片描述
    我们来实践第一个案例:
    一、导入要使用到的matplotlib库和numpy

导入matplotlib库简写为plt

导入numpy 简写为np,代码如下:

import matplotlib.pyplot as plt
import numpy as np

点击Run,正常运行

二、基本图表

2.用 plot 方法画出 x=(0,10)间 sin 的图像,输入代码:

x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x));

点击Run,运行效果如图:
在这里插入图片描述

后续案例请按顺序执行,因为部分案例的变量可能依赖前面案例的变量值。

3.用点加线的方式画出x=(0,10)间sin的图像

plt.plot(x, np.sin(x), '-o');

点击Run,运行效果如图:
在这里插入图片描述
页面效果如图:
在这里插入图片描述
4.用scatter方法画出x=(0,10)间sin的点图像

plt.scatter(x, np.sin(x));

在这里插入图片描述
5.用饼图的面积及颜色展示一组4维数据

rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)

plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
            cmap='viridis')
plt.colorbar(); # 展示色阶

在这里插入图片描述
6.绘制一组误差为±0.8的数据的误差条图

x = np.linspace(0, 10, 50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.errorbar(x, y, yerr=dy, fmt='.k')

在这里插入图片描述
7.绘制一个柱状图

x = [1,2,3,4,5,6,7,8]
y = [3,1,4,5,8,9,7,2]
label=['A','B','C','D','E','F','G','H']
plt.bar(x,y,tick_label = label);

在这里插入图片描述
8.绘制一个水平方向柱状图

plt.barh(x,y,tick_label = label);//同样使用与7例中的变量,与7对比,只多一个h

在这里插入图片描述
9.绘制1000个随机值的直方图

data = np.random.randn(1000)
plt.hist(data);

在这里插入图片描述
10.设置直方图分30个bins,并设置为频率分布

plt.hist(data, bins=30,histtype='stepfilled', density=True)
plt.show();

在这里插入图片描述
11.在一张图中绘制3组不同的直方图,并设置透明度

x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(alpha=0.3, bins=40, density = True)
plt.hist(x1, **kwargs);
plt.hist(x2, **kwargs);
plt.hist(x3, **kwargs);

在这里插入图片描述
12.绘制一张二维直方图

mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30);

在这里插入图片描述
13.绘制一张设置网格大小为30的六角形直方图

plt.hexbin(x, y, gridsize=30);

在这里插入图片描述

三、自定义图表元素

14.绘制x=(0,10)间sin的图像,设置线性为虚线

x = np.linspace(0,10,100)
plt.plot(x,np.sin(x),'--');

在这里插入图片描述
15设置y轴显示范围为(-1.5,1.5)

x = np.linspace(0,10,100)
plt.plot(x, np.sin(x))
plt.ylim(-1.5, 1.5);

在这里插入图片描述
16.设置x,y轴标签variable x,value y

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y, label='sin(x)')
plt.xlabel('variable x');
plt.ylabel('value y');

在这里插入图片描述
17.设置图表标题“三角函数”

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y, label='sin(x)')
plt.title('三角函数');

在这里插入图片描述
因为使用了中文,我们看到,三角函数四个字变成了乱码,解决办法:

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
font={'family':'SimHei'} #方便图中中文显示
plt.rc('font',**font)#方便图中中文显示,注意文中格式为UTF-8
plt.plot(x, y, label='sin(x)')
plt.title('三角函数');

在这里插入图片描述
18.显示网格

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.grid()

在这里插入图片描述
19.绘制平行于x轴y=0.8的水平参考线

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.axhline(y=0.8, ls='--', c='r')

在这里插入图片描述
20.绘制垂直于x轴x<4 and x>6的参考区域,以及y轴y<0.2 and y>-0.2的参考区域

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.axvspan(xmin=4, xmax=6, facecolor='r', alpha=0.3) # 垂直x轴
plt.axhspan(ymin=-0.2, ymax=0.2, facecolor='y', alpha=0.3);  # 垂直y轴

在这里插入图片描述
21.添加注释文字sin(x)

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.text(3.2, 0, 'sin(x)', weight='bold', color='r');

在这里插入图片描述
22.用箭头标出第一个峰值

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.annotate('maximum',xy=(np.pi/2, 1),xytext=(np.pi/2+1, 1),
             weight='bold',
             color='r',
             arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'));

在这里插入图片描述

四、自定义图例

23.在一张图里绘制sin,cos的图形,并展示图例

x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()

ax.plot(x, np.sin(x), label='sin')
ax.plot(x, np.cos(x), '--', label='cos')
ax.legend();

在这里插入图片描述
24.调整图例在左上角展示,且不显示边框

ax.legend(loc='upper left', frameon=False);
fig

在这里插入图片描述
25.调整图例在画面下方居中展示,且分成2列

ax.legend(frameon=False, loc='lower center', ncol=2)
fig

在这里插入图片描述
26.绘制的图像,并只显示前2者的图例
第一个方法

y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)
# lines 是 plt.Line2D 类型的实例的列表
plt.legend(lines[:2], ['first', 'second']);

第二个方法

y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
plt.plot(x, y[:, 0], label='first')
plt.plot(x, y[:, 1], label='second')
plt.plot(x, y[:, 2:])
plt.legend(framealpha=1, frameon=True);

在这里插入图片描述
27.将图例分不同的区域展示

fig, ax = plt.subplots()

lines = []
styles = ['-', '--', '-.', ':']
x = np.linspace(0, 10, 1000)

for i in range(4):
    lines += ax.plot(x, np.sin(x - i * np.pi / 2),styles[i], color='black')
ax.axis('equal')

# 设置第一组标签
ax.legend(lines[:2], ['line A', 'line B'],
          loc='upper right', frameon=False)

# 创建第二组标签
from matplotlib.legend import Legend
leg = Legend(ax, lines[2:], ['line C', 'line D'],
             loc='lower right', frameon=False)
ax.add_artist(leg);

在这里插入图片描述

五、自定义色阶

28.展示色阶

x = np.linspace(0, 10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])

plt.imshow(I)
plt.colorbar();

在这里插入图片描述
29.改变配色为’gray’

plt.imshow(I, cmap='gray');

在这里插入图片描述
30.将色阶分成6个离散值显示

plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
plt.colorbar()
plt.clim(-1, 1);

在这里插入图片描述

六、多子图

31.在一个1010的画布中,(0.65,0.65)的位置创建一个0.20.2的子图

ax1 = plt.axes()
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])

在这里插入图片描述
32.在2个子图中,显示sin(x)和cos(x)的图像

fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))

x = np.linspace(0, 10)
ax1.plot(np.sin(x));
ax2.plot(np.cos(x));

在这里插入图片描述
33.用for创建6个子图,并且在图中标识出对应的子图坐标
方法一

for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')

方法二

fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 7):
   ax = fig.add_subplot(2, 3, i)
   ax.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')

在这里插入图片描述
34.设置相同行和列共享x,y轴

fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')

在这里插入图片描述
35.用[]的方式取出每个子图,并添加子图座标文字

for i in range(2):
    for j in range(3):
        ax[i, j].text(0.5, 0.5, str((i, j)),fontsize=18, ha='center')
fig

在这里插入图片描述
36.组合绘制大小不同的子图,样式如下

grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
plt.subplot(grid[0, 0])
plt.subplot(grid[0, 1:])
plt.subplot(grid[1, :2])
plt.subplot(grid[1, 2]);

在这里插入图片描述
37.显示一组二维数据的频度分布,并分别在x,y轴上,显示该维度的数据的频度分布

mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 3000).T

# Set up the axes with gridspec
fig = plt.figure(figsize=(6, 6))
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)

# scatter points on the main axes
main_ax.scatter(x, y,s=3,alpha=0.2)

# histogram on the attached axes
x_hist.hist(x, 40, histtype='stepfilled',
            orientation='vertical')
x_hist.invert_yaxis()

y_hist.hist(y, 40, histtype='stepfilled',
            orientation='horizontal')
y_hist.invert_xaxis()

在这里插入图片描述

七、三维图像

38.创建一个三维画布

from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection='3d')

在这里插入图片描述
39.绘制一个三维螺旋线

ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline);

在这里插入图片描述
40.绘制一组三维点

ax = plt.axes(projection='3d')
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');

在这里插入图片描述

八、宝可梦数据集可视化

41案例开始,需要使用文档Pokemon.xlsx里面的800条数据,需要的朋友可以从这里下载
https://download.csdn.net/download/qq_26665293/12137479
41.展示前5个宝可梦的Defense,Attack,HP的堆积条形图

#导入文档
import pandas as pd
df=pd.read_excel('Pokemon.xlsx')

pokemon = df['Name'][:5]
hp = df['HP'][:5]
attack = df['Attack'][:5]
defense = df['Defense'][:5]
ind = [x for x, _ in enumerate(pokemon)]

plt.figure(figsize=(10,10))
plt.bar(ind, defense, width=0.8, label='Defense', color='blue', bottom=attack+hp)
plt.bar(ind, attack, width=0.8, label='Attack', color='gold', bottom=hp)
plt.bar(ind, hp, width=0.8, label='Hp', color='red')

plt.xticks(ind, pokemon)
plt.ylabel("Value")
plt.xlabel("Pokemon")
plt.legend(loc="upper right")
plt.title("5 Pokemon Defense & Attack & Hp")

plt.show()

在这里插入图片描述
42.展示前5个宝可梦的Attack,HP的簇状条形图

N = 5
pokemon_hp = df['HP'][:5]
pokemon_attack = df['Attack'][:5]

ind = np.arange(N)
width = 0.35       
plt.bar(ind, pokemon_hp, width, label='HP')
plt.bar(ind + width, pokemon_attack, width,label='Attack')

plt.ylabel('Values')
plt.title('Pokemon Hp & Attack')

plt.xticks(ind + width / 2, (df['Name'][:5]),rotation=45)
plt.legend(loc='best')
plt.show()

在这里插入图片描述
43.展示前5个宝可梦的Defense,Attack,HP的堆积图

x = df['Name'][:4]
y1 = df['HP'][:4]
y2 = df['Attack'][:4]
y3 = df['Defense'][:4]

labels = ["HP ", "Attack", "Defense"]

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3)
ax.legend(loc='upper left', labels=labels)
plt.xticks(rotation=90)
plt.show()

在这里插入图片描述
44.公用x轴,展示前5个宝可梦的Defense,Attack,HP的折线图

x = df['Name'][:5]
y1 = df['HP'][:5]
y2 = df['Attack'][:5]
y3 = df['Defense'][:5]

# Create two subplots sharing y axis
fig, (ax1, ax2,ax3) = plt.subplots(3, sharey=True)

ax1.plot(x, y1, 'ko-')
ax1.set(title='3 subplots', ylabel='HP')

ax2.plot(x, y2, 'r.-')
ax2.set(xlabel='Pokemon', ylabel='Attack')

ax3.plot(x, y3, ':')
ax3.set(xlabel='Pokemon', ylabel='Defense')

plt.show()

在这里插入图片描述
45.展示前15个宝可梦的Attack,HP的折线图

plt.plot(df['HP'][:15], '-r',label='HP')
plt.plot(df['Attack'][:15], ':g',label='Attack')
plt.legend();

在这里插入图片描述
46.用scatter的x,y,c属性,展示所有宝可梦的Defense,Attack,HP数据

x = df['Attack']
y = df['Defense']
colors = df['HP']

plt.scatter(x, y, c=colors, alpha=0.5)
plt.title('Scatter plot')
plt.xlabel('HP')
plt.ylabel('Attack')
plt.colorbar();

在这里插入图片描述
47.展示所有宝可梦的攻击力的分布直方图,bins=10

x = df['Attack']
num_bins = 10
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.title('Histogram')
plt.xlabel('Attack')
plt.ylabel('Value')
plt.show()

在这里插入图片描述
48.展示所有宝可梦Type 1的饼图

plt.figure(1, figsize=(8,8))
df['Type 1'].value_counts().plot.pie(autopct="%1.1f%%")
plt.legend()

在这里插入图片描述
49.展示所有宝可梦Type 1的柱状图

ax = df['Type 1'].value_counts().plot.bar(figsize = (12,6),fontsize = 14)
ax.set_title("Pokemon Type 1 Count", fontsize = 20)
ax.set_xlabel("Pokemon Type 1", fontsize = 20)
ax.set_ylabel("Value", fontsize = 20)

plt.show()

在这里插入图片描述
50.展示综合评分最高的10只宝可梦的系数间的相关系数矩阵

import seaborn as sns

top_10_pokemon=df.sort_values(by='Total',ascending=False).head(10)
corr=top_10_pokemon.corr()

fig, ax=plt.subplots(figsize=(10, 6))
sns.heatmap(corr,annot=True)
ax.set_ylim(9, 0)
plt.show()

在这里插入图片描述
matplotlib 可以绘制出很多漂亮的地图。如下图:
在这里插入图片描述
有兴趣的朋友可以参考另一篇文章:
Python使用 matplotlib的basemap绘图之一–几行代码画世界地图和中国地图

还可以根据人口数据形成人口热力图,如图:
在这里插入图片描述
具体参考:
Python使用 matplotlib的basemap绘图之二–画美国地图和中国人口热力图

本文已提供jupyter notebook实践过程的完整代码及注解,需要的朋友自行下载。也可以按文章自行实践。
50题matplotlib从入门到精通.ipynb

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值