matplotlib从绘图到排版

绘图

线与填充

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
data_obj = {'x': x,
            'y1': 2 * x + 1,
            'y2': 3 * x + 1.2
            ,'mean': 0.5 * x * np.cos(2*x) + 2.5 * x + 1.1
            }
fig, ax = plt.subplots()
#填充两条线之间的颜色
ax.fill_between('x', 'y1', 'y2', color='yellow', data=data_obj)

# Plot the "centerline" with `plot`
ax.plot('x', 'mean', color='black', data=data_obj)
plt.show()

在这里插入图片描述

散点图

常用参数

x,y:表示的是shape大小为(n,)的数组,也就是我们即将绘制散点图的数据点,输入数据。

s:表示的是大小,是一个标量或者是一个shape大小为(n,)的数组,可选,默认20。

c:表示的是色彩或颜色序列,可选,默认蓝色’b’。但是c不应该是一个单一的RGB数字,也不应该是一个RGBA的序列,因为不便区分。c可以是一个RGB或RGBA二维行数组。

marker:MarkerStyle,表示的是标记的样式,可选,默认’o’。

cmap:Colormap,标量或者是一个colormap的名字,cmap仅仅当c是一个浮点数数组的时候才使用。如果没有申明就是image.cmap,可选,默认None。

norm:Normalize,数据亮度在0-1之间,也是只有c是一个浮点数的数组的时候才使用。如果没有申明,就是默认None。

vmin,vmax:标量,当norm存在的时候忽略。用来进行亮度数据的归一化,可选,默认None。

alpha:标量,0-1之间,可选,默认None。

linewidths:也就是标记点的长度,默认None。

marker

1. 1. 1.常用颜色:
'b' blue 蓝
'g' green 绿
'r' red 红
'c' cyan 蓝绿
'm' magenta 洋红
'y' yellow 黄
'k' black 黑
'w' white 白

2. 2. 2.
在这里插入图片描述
3. l i n e s t y l e 3.linestyle 3.linestyle
'-' solid line style 实线
'--' dashed line style 虚线
'-.' dash-dot line style 点画线
':' dotted line style 点线

import matplotlib.pyplot as plt
import numpy as np
x=np.arange(10)
y=np.random.randn(10)*10
plt.scatter(x,y,color="red",marker="+")
plt.show()

在这里插入图片描述

频度分布图

hist官网
函数:matplotlib.pyplot.hist(x,bins=None,range=None, density=None, bottom=None, histtype=‘bar’, align=‘mid’, log=False, color=None, label=None, stacked=False, normed=None)
常用参数:

x: 数据集,最终的直方图将对数据集进行统计
bins: 统计的区间分布

range: tuple, 显示的区间,range在没有给出bins时生效

**density**: bool,默认为false,显示的是频数统计结果,
为True	则显示频率统计结果,这里需要注意,
频率统计结果=区间数目/(总数	*区间宽度),
和normed效果一致,官方推荐使用density

facecolor:例如'g',颜色

alpha:透明度

histtype: 可选{'bar', 'barstacked', 'step', 'stepfilled'}之一,默认为	bar,推荐使用默认配置,step使用的是梯状,stepfilled则会对梯状	内部进行填充,效果与bar类似

align: 可选{'left', 'mid', 'right'}之一,默认为'mid',
控制柱状图的水平分布,left或者right,会有部分空白区域,
推荐使用默认

log: bool,默认False,即y坐标轴是否选择指数刻度

stacked: bool,默认为False,是否为堆积状图

点线图

plot官网

常用参数

plot(x, y, color=‘green’, marker=‘o’, linestyle=‘dashed’,
linewidth=2, markersize=12)

实例

import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

在这里插入图片描述

柱状图

常用参数

x,包含所有柱子的下标的列表,也就是每个柱子的标签
left        每个柱x轴左边界
bottom      每个柱y轴下边界
height, 包含所有柱子的高度值的列表
width, 每个柱子的宽度。 可以指定一个固定值, 
     那么所有的柱子都是一样的宽。 或者设置一个列表, 
     这样可以分别对每个柱子设定不同的宽度
align, 柱子对齐方式,有两个可选值:center 和 edge
color, 柱子的颜色,可传入一个固定值或一个列表
edgecolor, 柱子的边框颜色,可传入一个固定值或一个列表
linewidth, 每根柱子的边框宽度。 如果没有设置,默认没有边框
tick_label, 每根柱子上显示的标签, 默认是没有
xerr        x方向error bar
yerr        y方向error bar
ecolor      error bar颜色
capsize     error bar横线宽度(default 3)

实例

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np
plt.subplot(221)
#频度分布图
mu,sigma=100,15
x=mu+sigma*np.random.randn(10000)
# the histogram of the data
n, bins, patches=plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)  #要统计的数组,多少块,显示频率1或频数0,颜色,透明度
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('频度分布图',fontproperties="KaiTi",size=22)
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.subplot(222)
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
plt.title('散点气泡图',fontproperties="KaiTi",size=22)
plt.scatter('a', 'b', c='c', s='d', data=data)  #c参数是颜色,s参数是大小
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.subplot(223)
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)
t = np.arange(0., 5., 0.2)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.title('点线图',fontproperties="KaiTi",size=22)
plt.subplot(224)
plt.title('柱状图',fontproperties="KaiTi",size=22)
N = 5
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 = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
             bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'),bbox_to_anchor=(1.04,0.3))
plt.tight_layout()    #使得图与图之间不重叠
plt.show()

排版

图例

legend官网
常用参数

'loc:图例位置,可取(‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center , right’, ‘lower center’, ‘upper center’, ‘center’) ;若是使用了bbox_to_anchor,则这项就无效了

fontsize: int或float或{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},字体大小;

frameon: 是否显示图例边框,

ncol: 图例的列的数量,默认为1,

title: 为图例添加标题

shadow: 是否为图例边框添加阴影,

markerfirst: True表示图例标签在句柄右侧,false反之,

markerscale: 图例标记为原图标记中的多少倍大小,

numpoints: 表示图例中的句柄上的标记点的个数,一般设为1,

fancybox: 是否将图例框的边角设为圆形

framealpha: 控制图例框的透明度

borderpad: 图例框内边距

labelspacing: 图例中条目之间的距离

handlelength: 图例句柄的长度

bbox_to_anchor
在这里插入图片描述
实例
里面也介绍了如何使得保存的图像分辨率提高

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
plt.figure()
t = np.arange(0., 5., 0.2)
matplotlib.rcParams["font.family"]="KaiTi"
# red dashes, blue squares and green triangles
p=plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.xlabel("X轴",size=12)
plt.ylabel("Y轴",size=12)
plt.legend((p[0],p[1],p[2]),(r"$t$",r"$t^2$",r"$t^3$")
           ,loc='center'
           ,bbox_to_anchor=(1.2,0.2)
           , fontsize=12
           , frameon=1
           , fancybox=True
           , framealpha=0.2
           , borderpad=0.3
           , ncol=1
           , markerfirst=True
           , markerscale=1
           , numpoints=1
           , handlelength=3.5
           ,title="图例"
     )
# plt.rcParams['savefig.dpi'] = 300 #图片像素
# plt.rcParams['figure.dpi'] = 300 #分辨率
plt.tight_layout()
plt.savefig("lig.png",dpi=300)
plt.show()

或者

plt.subplot(211)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")
plt.tight_layout()
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
           ncol=2, mode="expand", borderaxespad=0.)

使用matplotlib.pyplot实现画折线图的一个实用示例

添加中文

import matplotlib.pyplot as plt
plt.xlabel("x轴",fontproperties="KaiTi",size=14)
plt.ylabel("y轴", fontproperties="SimSun",size=14) # 步骤一    (宋体)
plt.title("标题", fontproperties="SimHei",size=36) #          (黑体)
plt.show()

一些中文字体的英文名

宋体 SimSun
黑体 SimHei
微软雅黑 Microsoft YaHei
微软正黑体 Microsoft JhengHei
新宋体 NSimSun
新细明体 PMingLiU
细明体 MingLiU
标楷体 DFKai-SB
仿宋 FangSong
楷体 KaiTi
隶书:LiSu
幼圆:YouYuan
华文细黑:STXihei
华文楷体:STKaiti
华文宋体:STSong
华文中宋:STZhongsong
华文仿宋:STFangsong
方正舒体:FZShuTi
方正姚体:FZYaoti
华文彩云:STCaiyun
华文琥珀:STHupo
华文隶书:STLiti
华文行楷:STXingkai
华文新魏:STXinwei

Axes 列表

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right',xlim=[0.5, 4.5], ylim=[-2, 8],
       ylabel='Y-Axis', xlabel='X-Axis')
plt.show()

在这里插入图片描述
实例

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)
fig,axes=plt.subplots(nrows=2, ncols=2)
axes[0,0].plot(x, y_sin)
axes[0,1].plot(x, y_sin, 'go--', linewidth=2, markersize=12)
axes[1,0].plot(x, y_cos, color='red', marker='+', linestyle='dashed')
#ax2的第三个参数是 MATLAB风格的绘图,对应ax3上的颜色,marker,线型。
plt.show()

在这里插入图片描述

添加箭头

Python学习笔记(4)——Matplotlib中的annotate(注解)的用法

import matplotlib.pyplot as plt
import numpy as np

plt.subplot()
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2,c="g")
plt.annotate('局部最大值',fontproperties="KaiTi"
             ,xy=(2, 1)
             , xytext=(3, 1.5)
             ,arrowprops=dict(facecolor='black'
                              , shrink=0.02  #箭头两端收缩的百分比(占总长)
                              ,width=0.1     #尾部宽度
                              ,headwidth=5   #箭头宽度
                              )
             )
plt.ylim(-2, 2)
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值