绘图与可视化入手教程

Matplotlib

导入包

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 在ipython环境(jupyter基于ipython)下直接显示图片
%matplotlib inline

import matplotlib
matplotlib.__version__ #查看版本号

创建画布与创建子图

#简单画图
data=np.arange(10)
plt.plot(data)

在这里插入图片描述
当第一次执行plt.xxx()画图代码时,系统会去判断是否已经有了figure对象,如果没有,系统会自动创建一个figure对象,并且在这个figure之上,自动创建一个axes坐标系(注意:默认创建一个figure对象,一个axes坐标系)。所以默认的只能画一张图。

创建画布

plt.figure()—在plt中绘制一张图片

figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs)

num:图像编号或名称,数字为编号 ,字符串为名称
figsize:指定figure的宽和高,单位为英寸;
dpi:参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80;1英寸等于2.5cm,A4纸是 21*30cm的纸张
facecolor:背景颜色
edgecolor:边框颜色
frameon:是否显示边框

#手动创建一个figure对象
figure = plt.figure(figsize=(4,3))

plt.subplot–创建单个子图

subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)
在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
 
plt.subplot(221)
plt.plot(x, x)
#作图2
plt.subplot(222)
plt.plot(x, -x)
#作图3
plt.subplot(223)
plt.plot(x, x ** 2)
plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图4
plt.subplot(224)
plt.plot(x, np.log(x))
plt.show()

在这里插入图片描述

plt.subplots–创建多个子图

subplots参数与subplots相似。两者都可以规划figure划分为n个子图,但每条subplot命令只会创建一个子图,而一条subplots就可以将所有子图创建好。

import numpy as np
import matplotlib.pyplot as plt
 
x = np.arange(0, 100)
#划分子图
fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
ax2=axes[0,1]
ax3=axes[1,0]
ax4=axes[1,1]
 
#作图1
ax1.plot(x, x)
#作图2
ax2.plot(x, -x)
#作图3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图4
ax4.plot(x, np.log(x))
plt.show()
figure().add_subplot方法----给figure新增子图

fig.add_subplot(*args, **kwargs) 的作用与subplot一样,用于新增子图。具体如下:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#新建figure对象
fig=plt.figure()
#新建子图1
ax1=fig.add_subplot(2,2,1)
ax1.plot(x, x)
#新建子图2
ax2=fig.add_subplot(2,2,2)
ax2.plot(x, x ** 2)
ax2.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#新建子图3
ax3=fig.add_subplot(2,2,3)
ax3.plot(x, np.log(x))
plt.show()

画布内容

第二部分是绘图的主体部分。其中添加标题,坐标轴名称,绘制图形等步骤是并列的,没有先后顺序,可以先绘制图形,也可以先添加各类标签。但是添加图例一定要在绘制图形之后。

plt.subplots()画布

在这里插入图片描述

fig.add_subplot()

颜色、标记、线类型

plot(x,y,color=‘k’,linestyle=‘d’,marker=‘o’)

axes=plt.subplot(1,1,1)
# axes.plot(np.arange(5),np.arange(5)**2)
axes.plot(np.random.randn(30).cumsum(),linestyle='-',marker='*',color='b') #linestype(-- - -.  :)
刻度、标尺和图例

改变x轴刻度,最简单的方式是使用set_xtickes和set_xticklables
set_xtickes表示在数据范围内设定刻度的位置,set_xtickeslabels为标签赋值
legend()添加图例

axes=plt.subplot(1,1,1)
# axes.plot(np.arange(5),np.arange(5)**2)
axes.plot(np.random.randn(30).cumsum(),linestyle='-',marker='*',color='b') #linestype(-- - -.  :)
l=axes.set_xticks([0,10,20,30,40])
axes.set_title('这是我画的第一个图')
axes.set_xticklabels(['one','two','three','four','five'],fontsize='small',rotation=30)
axes.set_xlabel('stages')


#
propes={
    'ylabel':"y值",
    'xlabel':'值'
}
axes.set(**propes)

不同类型的图

散点图

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, alpha=None, **kwargs)

# 绘制散点图查看身高与体重的关系
plt.scatter(data1['身高'], data1['体重'], color="c", marker="*")
plt.xlabel('height(cm)')                             # plt.xlabel 设置x轴标签
plt.ylabel('weight(kg)')                             # plt.ylabel 设置y轴标签
plt.title('身高体重关系示意图')

折线图

matplotlib.pyplot.plot(*args, **kwargs)

# 折线图
plt.plot(data2_x, data2_y, linestyle='--')

直方图

matplotlib.pyplot.hist(x, y)

# 正态分布的数据
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75)

plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)  # 设置网格

条形统计图

matplotlib.pyplot.bar(left,height,width=0.8,bottom=None,hold=None,data=None,**kwargs)

# 例
names = ['高一', '高二', '高三']
values = [879, 517, 725]

plt.bar(names, values, color='orange', width=0.7)
plt.title('捐款金额')

箱型图

matplotlib.pyplot.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None,meanline=None, labels=None, …)

data3 = np.random.randn(10000)

plt.boxplot(data3)

饼图

matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, …)

# 频次或频率
size = [1, 2, 3, 4, 5]  # 各类别占比
# 各类别标签
label = ['猫', '狗', '牛', '羊', '马']
# 每个类别要绘制的颜色
color = ['lightblue', 'lightgreen', 'lightyellow', 'pink', 'orange']  # 各类别颜色
explode = (0, 0, 0, 0, 0.1)  # 各类别的偏移半径

# 绘制饼状图
plt.pie(size, colors=color, explode=explode,
        labels=label, shadow=False, autopct='%.2f%%')

雷达图

# 创建画布
fig = plt.figure(figsize=(5, 5))

# 玩家数据(0-10分)
data4 = np.array([[3.2, 1.7, 1.9, 2.5, 8.0],
                  [8.2, 6.9, 5.4, 1.7, 3.6],
                  [5.2, 4.2, 8.7, 0.5, 1.7],
                  [7.4, 5.4, 4.1, 3.5, 6.2]])
n, k = data4.shape

# 各维度名称
names = ['打钱速度', '击杀助攻', '输出能力', '控制时长', '吸收伤害']

ax = fig.add_subplot(111, polar=True)  # 生产极坐标以角度和半径的坐标
angles = np.linspace(0, 2*np.pi, k, endpoint=False)  # 创建等差数列绘制周长
angles = np.concatenate((angles, [angles[0]]))  # 闭合

Linestyle = ['bo-', 'r+:', 'gD--', 'yv-.']  # 点线形状
Fillcolor = ['b', 'r', 'g', 'y']  # 填充颜色\点线颜色

for i in range(n):
    data = np.concatenate((data4[i], [data4[i][0]])) # 拼接数组闭合
    ax.plot(angles, data, Linestyle[i], linewidth=2)  # 绘制各个区域轮廓
    ax.fill(angles, data, facecolor=Fillcolor[i], alpha=0.25)  # 在各个区域填充颜色

ax.set_thetagrids(angles * 180/np.pi, names)  # 显示类别名字
ax.set_title("玩家能力值对比图", va='bottom')  # 设定标题
ax.set_rlim(0, 11)  # 设置各指标的最终范围
ax.grid(True)  # 显示网格
# 创建画布
fig = plt.figure(figsize=(12, 7))

# --------添加第一个子图--------
sp1 = fig.add_subplot(2, 3, 1)

# 第一个子图的属性调整和绘制
# (1)设置标题
plt.title("第一个子图:散点图")

# (2)x轴和y轴名称
plt.xlabel("x轴标签")
plt.ylabel("y轴标签")

# (3)x轴和y轴的刻度
plt.xticks([1, 2, 3])
plt.yticks(range(2, 9, 2))

# (4)绘制图形
plt.scatter([1, 2, 3], [4, 8, 1], color="g", marker="D", label="point1")
plt.scatter([1, 2, 3], [7, 2, 5], color="r", marker="o", label="point2")

# (5)设置图例
plt.legend(loc=1)

# --------添加第二个子图--------
sp2 = fig.add_subplot(2, 3, 2)

# 第二个子图的属性调整和绘制
# (1)设置标题
plt.title("第二个子图:折线图")

# (2)x轴和y轴名称
plt.xlabel("x轴标签")
plt.ylabel("y轴标签")

# (3)x轴和y轴的刻度
plt.xticks([1, 2, 3])
plt.yticks(range(2, 9, 2))

# (4)绘制图形
plt.plot([1, 2, 3], [4, 8, 1],
         color="g", linestyle="--",
         marker="D", label="line1")

plt.plot([1, 2, 3], [7, 2, 5],
         color="m", linestyle=":",
         marker="x", label="line2")

# (5)设置图例
plt.legend(loc=1)

# --------添加第三个子图--------
sp3 = fig.add_subplot(2, 3, 3)

# 第三个子图的属性调整和绘制
# (1)设置标题
plt.title("第三个子图:直方图")

# (2)x轴和y轴名称
plt.xlabel("x轴标签")
plt.ylabel("y轴标签")

# (3)x轴和y轴的刻度
plt.xticks(np.arange(-5, 6))

# (4)绘制图形
plt.hist(np.random.randn(100000), 1000)

# (5)添加注释和箭头
# plt.text(2, 370, '众数')
plt.annotate('众数', xy=(0.0, 360), xytext=(2, 350),
            arrowprops=dict(facecolor='black', shrink=0.01))

# --------添加第四个子图--------
sp4 = fig.add_subplot(2, 3, 4)

# 第四个子图的属性调整和绘制
# (1)设置标题
plt.title("第四个子图:条形图")

# (2)x轴和y轴名称
plt.xlabel("城市")
plt.ylabel("人口")

# (3)x轴和y轴的刻度

# (4)绘制图形
plt.bar(["北京", "郑州", "驻马店"], [2000, 1500, 1000])

# --------添加第五个子图--------
sp5 = fig.add_subplot(2, 3, 5)

# 第五个子图的属性调整和绘制
# (1)设置标题
plt.title("第五个子图:饼图")

# (2)x轴和y轴名称

# (3)x轴和y轴的刻度

# (4)绘制图形
plt.pie([2000, 1500, 1000], labels=["北京", "郑州", "驻马店"], autopct="%.2f%%")

# --------添加第六个子图--------
sp6 = fig.add_subplot(2, 3, 6)

# 第六个子图的属性调整和绘制
# (1)设置标题
plt.title("第六个子图:箱线图")

# (2)x轴和y轴名称
plt.xlabel("城市")
plt.ylabel("人口")

# (3)x轴和y轴的刻度

# (4)绘制图形
plt.boxplot([np.random.randn(100), np.random.randn(100), np.random.randn(100)], meanline=True)

# --------统一调整子图间距--------
fig.subplots_adjust(wspace=0.3,hspace=0.5)

# --------保存图片--------
fig.savefig("sixsixsix.png")

Seaborn

series.plot()
plot.bar()垂直柱状图
plot.barh()水平柱状图
plot.hist()直方图
plot.density()密度图
plot.regplot()散点图
sns.factorplot()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值