-
Python绘图库Matplotlib.pyplot之网格线设置(plt.grid())
2018-07-16 10:28:31首先导入需要用到的库,matplotlib.pyplot是必须的,Numpy是为了生成画布用的。 import numpy as np import matplotlib.pyplot as plt 生成网格 plt.gcf().set_facecolor(np.ones(3)* 240 /...很多时候为了可视化效果的美观,就不得不从细节上下手,这里我们就介绍一下这些细节之一的网格线。
首先导入需要用到的库,matplotlib.pyplot是必须的,Numpy是为了生成画布用的。
import numpy as np import matplotlib.pyplot as plt
生成网格
plt.gcf().set_facecolor(np.ones(3)* 240 / 255) # 生成画布的大小 plt.grid() # 生成网格 plt.show()
参数
matplotlin.pyplot.grid(b, which, axis, color, linestyle, linewidth, **kwargs)
grid()参数有很多,这里只列举了我此次工作中用到的几个:
b : 布尔值。就是是否显示网格线的意思。官网说如果b设置为None, 且kwargs长度为0,则切换网格状态。但是没弄明白什 么意思。如果b设置为None,但是又给了其它参数,则默认None值失效。
which : 取值为'major', 'minor', 'both'。 默认为'major'。看别人说是显示的,我的是Windows7下,用Sublime跑的,minor 只是一个白画板,没有网格,major和both也没看出什么效果,不知道为什么。
axis : 取值为‘both’, ‘x’,‘y’。就是想绘制哪个方向的网格线。不过我在输入参数的时候发现如果输入x或y的时候, 输入的是哪条轴,则会隐藏哪条轴
color : 这就不用多说了,就是设置网格线的颜色。或者直接用c来代替color也可以。
linestyle :也可以用ls来代替linestyle, 设置网格线的风格,是连续实线,虚线或者其它不同的线条。 |
'-'
|'--'
|'-.'
|':'
|'None'
|' '
|''
]linewidth : 设置网格线的宽度
设置axis='y'
plt.grid(axis="y") plt.show()
设置axis='x'
设置color='r'
plt.grid(c='r') plt.show()
红色
plt.grid(c='g') plt.show()
绿色
设置linestyle
plt.grid(linestyle='-.') plt.show()
plt.grid(ls='--') plt.show()
因为b和which没有显示效果。所以这里就不上图了。
--------------------------更******新--------------------------
今天又试了下,当which='major'的时候,是可以显示网格线的。同时感谢机器不学习o_o的指导,在which="minor"时,需要设置次刻度线。
plt.grid(axis='y', which='major') plt.show()
plt.grid(axis="x", which="major") plt.show()
which='minor'
ax = plt.gca() ax.set_xlim(0, 10) miloc = plt.MultipleLocator(1) ax.xaxis.set_minor_locator(miloc) ax.grid(axis='x', which='minor') plt.show()
-
matplotlib.pyplot.plot()参数详解
2018-04-03 12:17:43在交互环境中查看帮助文档...import matplotlib.pyplot as plt help(plt.plot) 以下是对帮助文档重要部分的翻译: plot函数的一般的调用形式: #单条线: plot([x], y, [fmt], data=None, **kwargs) #多条线一...https://matplotlib.org/api/pyplot_summary.html
在交互环境中查看帮助文档:
import matplotlib.pyplot as plt help(plt.plot)
以下是对帮助文档重要部分的翻译:
plot函数的一般的调用形式:
#单条线: plot([x], y, [fmt], data=None, **kwargs) #多条线一起画 plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
可选参数[fmt] 是一个字符串来定义图的基本属性如:颜色(color),点型(marker),线型(linestyle),
具体形式 fmt = '[color][marker][line]'
fmt接收的是每个属性的单个字母缩写,例如:
plot(x, y, 'bo-') # 蓝色圆点实线
若属性用的是全名则不能用*fmt*参数来组合赋值,应该用关键字参数对单个属性赋值如:
plot(x,y2,color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)
plot(x,y3,color='#900302',marker='+',linestyle='-')
常见的颜色参数:**Colors**
也可以对关键字参数color赋十六进制的RGB字符串如 color='#900302'
============= =============================== character color ============= =============================== ``'b'`` blue 蓝 ``'g'`` green 绿 ``'r'`` red 红 ``'c'`` cyan 蓝绿 ``'m'`` magenta 洋红 ``'y'`` yellow 黄 ``'k'`` black 黑 ``'w'`` white 白 ============= ===============================
点型参数**Markers**,如:marker='+' 这个只有简写,英文描述不被识别
============= =============================== character description ============= =============================== ``'.'`` point marker ``','`` pixel marker ``'o'`` circle marker ``'v'`` triangle_down marker ``'^'`` triangle_up marker ``'<'`` triangle_left marker ``'>'`` triangle_right marker ``'1'`` tri_down marker ``'2'`` tri_up marker ``'3'`` tri_left marker ``'4'`` tri_right marker ``'s'`` square marker ``'p'`` pentagon marker ``'*'`` star marker ``'h'`` hexagon1 marker ``'H'`` hexagon2 marker ``'+'`` plus marker ``'x'`` x marker ``'D'`` diamond marker ``'d'`` thin_diamond marker ``'|'`` vline marker ``'_'`` hline marker ============= ===============================
线型参数**Line Styles**,linestyle='-'
============= =============================== character description ============= =============================== ``'-'`` solid line style 实线 ``'--'`` dashed line style 虚线 ``'-.'`` dash-dot line style 点画线 ``':'`` dotted line style 点线 ============= ===============================
样例1
函数原型:matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs) >>> plot('xlabel', 'ylabel', data=obj) 解释:All indexable objects are supported. This could e.g. be a dict, a pandas.DataFame or a structured numpy array. data 参数接受一个对象数据类型,所有可被索引的对象都支持,如 dict 等
import matplotlib.pyplot as plt import numpy as np '''read file fin=open("para.txt") a=[] for i in fin: a.append(float(i.strip())) a=np.array(a) a=a.reshape(9,3) ''' a=np.random.random((9,3))*2 #随机生成y y1=a[0:,0] y2=a[0:,1] y3=a[0:,2] x=np.arange(1,10) ax = plt.subplot(111) width=10 hight=3 ax.arrow(0,0,0,hight,width=0.01,head_width=0.1, head_length=0.3,length_includes_head=True,fc='k',ec='k') ax.arrow(0,0,width,0,width=0.01,head_width=0.1, head_length=0.3,length_includes_head=True,fc='k',ec='k') ax.axes.set_xlim(-0.5,width+0.2) ax.axes.set_ylim(-0.5,hight+0.2) plotdict = { 'dx': x, 'dy': y1 } ax.plot('dx','dy','bD-',data=plotdict) ax.plot(x,y2,'r^-') ax.plot(x,y3,color='#900302',marker='*',linestyle='-') plt.show()
样例2,
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 2*np.pi, 0.02) y = np.sin(x) y1 = np.sin(2*x) y2 = np.sin(3*x) ym1 = np.ma.masked_where(y1 > 0.5, y1) ym2 = np.ma.masked_where(y2 < -0.5, y2) lines = plt.plot(x, y, x, ym1, x, ym2, 'o') #设置线的属性 plt.setp(lines[0], linewidth=1) plt.setp(lines[1], linewidth=2) plt.setp(lines[2], linestyle='-',marker='^',markersize=4) #线的标签 plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), loc='upper right') plt.title('Masked line demo') plt.show()
例3 :圆
import numpy as np import matplotlib.pyplot as plt theta = np.arange(0, 2*np.pi, 0.01) xx = [1,2,3,10,15,8] yy = [1,-1,0,0,7,0] rr = [7,7,3,6,9,9] fig = plt.figure() axes = flg.add_subplot(111) i = 0 while i < len(xx): x = xx[i] + rr[i] *np.cos(theta) x = xx[i] + rr[i] *np.cos(theta) axes.plot(x,y) axes.plot(xx[i], yy[i], color='#900302', marker='*') i = i+1 width = 20 hight = 20 axes.arrow(0,0,0,hight,width=0.01,head_width=0.1,head_length=0.3,fc='k',ec='k') axes.arrow(0,0,width,0,width=0.01,head_width=0.1,head_length=0.3,fc='k',ec='k') plt.show()
-
matplotlib.pyplot
2020-03-12 09:14:401.matplotlib.pyplot.figure(num,…) 给窗口命名 2.matplotlib.pyplot.plot(x,y,colorpointline,…) 画直线:(x,y)坐标 图像颜色 图像中点和线的样式 3.matplotlib.pyplot.xlabel() matplotlib.pyplot.ylabel() 分别...1.matplotlib.pyplot.figure(num,…)
给窗口命名2.matplotlib.pyplot.plot(x,y,colorpointline,…)
画直线:(x,y)坐标 图像颜色 图像中点和线的样式3.matplotlib.pyplot.xlabel()
matplotlib.pyplot.ylabel()
分别给xy轴命名4.matplotlib.pyplot.title()
给图像起标题5.matplotlib.pyplot.show()
绘制6.matplotlib.pyplot.grid()
绘制网格7.matplotlib.pyplot.legend()
放置标签 -
Py之matplotlib.pyplot:matplotlib.pyplot的plt.legend函数的简介、使用方法之详细攻略
2021-01-04 23:41:54Py之matplotlib.pyplot:matplotlib.pyplot的plt.legend函数的简介、使用方法之详细攻略 目录 matplotlib.pyplot的plt.legend函数的简介 1、参数解释 2、源代码 matplotlib.pyplot的plt.legend函数的...Py之matplotlib.pyplot:matplotlib.pyplot的plt.legend函数的简介、使用方法之详细攻略
目录
matplotlib.pyplot的plt.legend函数的简介
matplotlib.pyplot的plt.legend函数的使用方法
matplotlib.pyplot的plt.legend函数的简介
legend模块定义了legend类,负责绘制与轴和/或图形相关的图例。Legend类是一个图例句柄和图例文本的容器,该函数是用来给当前图像添加图例内容。大多数用户通常会通过图例函数创建图例。图例处理程序映射指定如何在轴或图形中从artists(线、补丁等)创建图例句柄。默认的图例处理程序定义在legend_handler模块中。虽然默认的图例处理程序并没有覆盖所有的artists类型,但是可以定义自定义图例处理程序来支持任意对象。
plt.legend(loc='best',frameon=False) #frameon参数,去掉图例边框 plt.legend(loc='best',edgecolor='blue') #edgecolor参数,设置图例边框颜色 plt.legend(loc='best',facecolor='blue') #facecolor参数,设置图例背景颜色,若无边框,参数无效 plt.legend(["CH", "US"], title='China VS Us') #设置图例标题 plt.legend([p1, p2], ["CH", "US"]) #设置图例名字及对应关系
原始文档:https://matplotlib.org/api/legend_api.html?highlight=legend#module-matplotlib.legend
1、参数解释
参数 解释 具体应用 loc Location code string, or tuple (see below).图例所有figure位置
plt.legend(loc='upper center')
0: ‘best'
1: ‘upper right'
2: ‘upper left'
3: ‘lower left'
4: ‘lower right'
5: ‘right'
6: ‘center left'
7: ‘center right'
8: ‘lower center'
9: ‘upper center'
10: ‘center'prop the font property字体参数 fontsize the font size (used only if prop is not specified) fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
markerscale the relative size of legend markers vs. original 图例标记与原始标记的相对大小
markerfirst If True (default), marker is to left of the label. 如果为True,则图例标记位于图例标签的左侧
numpoints the number of points in the legend for line 为线条图图例条目创建的标记点数
scatterpoints the number of points in the legend for scatter plot 为散点图图例条目创建的标记点数
scatteryoffsets a list of yoffsets for scatter symbols in legend 为散点图图例条目创建的标记的垂直偏移量
frameon If True, draw the legend on a patch (frame). 控制是否应在图例周围绘制框架
fancybox If True, draw the frame with a round fancybox. 控制是否应在构成图例背景的FancyBboxPatch周围启用圆边
shadow If True, draw a shadow behind legend. 控制是否在图例后面画一个阴
framealpha Transparency of the frame. 控制图例框架的 Alpha 透明度
edgecolor Frame edgecolor. facecolor Frame facecolor. ncol number of columns 设置图例分为n列展示 borderpad the fractional whitespace inside the legend border 图例边框的内边距
labelspacing the vertical space between the legend entries 图例条目之间的垂直间距
handlelength the length of the legend handles 图例句柄的长度
handleheight the height of the legend handles 图例句柄的高度
handletextpad the pad between the legend handle and text 图例句柄和文本之间的间距
borderaxespad the pad between the axes and legend border 轴与图例边框之间的距离
columnspacing the spacing between columns 列间距 title the legend title bbox_to_anchor the bbox that the legend will be anchored.指定图例在轴的位置 bbox_transform the transform for the bbox. transAxes if None. 2、源代码
更新……
def legend Found at: matplotlib.pyplot @_copy_docstring_and_deprecators(Axes.legend) def legend(*args, **kwargs): return gca().legend(*args, **kwargs) # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
matplotlib.pyplot的plt.legend函数的使用方法1、基础用法
plt.figure() col_cou_len=len(Keys) plt.pie(x=Values,labels=Keys,colors=cols[:col_cou_len], startangle=90,shadow=True,autopct='%1.3f%%') plt.title(tit_name) plt.legend() plt.show()
-
matplotlib.pyplot.matshow 矩阵可视化实例
2020-09-16 16:56:45主要介绍了matplotlib.pyplot.matshow 矩阵可视化实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 -
关于import matplotlib.pyplot as plt的多种报错解决
2018-12-13 20:22:46本文针对由于版本、依赖库等造成的若干import matplotlib.pyplot as plt语句报错问题。 操作系统:win10 Python版本:3.7.0 matplotlib.pyplot 是常见的可视化工具之一,风格与MATLAB类似,可以方便的绘制图像、... -
matplotlib.pyplot.plot()参数使用详解
2020-09-16 11:19:19主要介绍了matplotlib.pyplot.plot()参数详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 -
matplotlib.pyplot绘制图像之同一图中多条曲线对比
2018-11-07 16:41:45绘制sinx和cosx # -*- coding:utf-8 -*- ...import matplotlib.pyplot as plt x = np.linspace(0, 2 * (np.pi)) #numpy.linspace(开始,终值(含终值)),个数) y1 = np.sin(x) y2 = np.cos(x) #画图 plt.title('C... -
matplotlib.pyplot 拉弧测试
2019-03-30 11:16:12import matplotlib.pyplot as plt import numpy as np def f(t): 'A damped exponential' s1 = np.cos(2 * np.pi * t) e1 = np.exp(-t) return s1 * e1 t1 = np.arange(0.0, 5.0, .2) l = plt.plot(t1, f... -
python-matplotlib.pyplot如何设置坐标轴范围
2019-04-08 18:33:28python-matplotlib.pyplot如何设置坐标轴范围 -
Python matplotlib.pyplot.hist函数 参数详解(超详细的!)
2019-04-03 11:17:40matplotlib.pyplot.hist函数 参数详解 函数内容 matplotlib.pyplot.hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, ... -
matplotlib.pyplot.subplots
2019-03-24 22:09:31matplotlib.pyplot.subplots -
matplotlib.pyplot.subplot
2019-03-28 01:30:37matplotlib.pyplot.subplot -
matplotlib.pyplot.annotate
2019-03-24 09:39:10matplotlib.pyplot.annotate -
matplotlib.pyplot.imshow
2020-07-19 17:32:07官方链接:...matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, *, filternorm=True, filterrad=4.0, -
pycharm使用matplotlib.pyplot不显示图形的解决方法
2020-09-20 00:08:47今天小编就为大家分享一篇pycharm使用matplotlib.pyplot不显示图形的解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 -
matplotlib.pyplot.hist参数详解
2020-01-30 18:56:11参考官方文档:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html#matplotlib.pyplot.hist matplot.pyplot.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=... -
matplotlib.pyplot.gca
2019-09-25 10:08:23matplotlib.pyplot.gca(**kwargs)[source] Get the current Axes instance on the current figure matching the given keyword args, or create one. See also matplotlib.figure.Figure.gca The figure's gca m... -
Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度
2020-09-20 15:54:29Matplotlib是Python提供的一个二维绘图库,所有类型的平面图,包括直方图、散点图、折线图、点图、热图...本文主要介绍了关于Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度的相关资料,需要的朋友可以参考下。 -
matplotlib.pyplot.xlim()、ylim()、axis()结构及用法||参数详解
2019-05-07 19:49:20matplotlib.pyplot.xlim() 官方文档 matplotlib.pyplot.xlim(*args, **kwargs) 获取或者是设定x座标轴的范围,当前axes上的座标轴。 有两种参数输入方式 plt.xlim(num1, num2) plt.xlim(xmin=num1,xmax=... -
matplotlib.pyplot.scatter API
2020-07-05 12:09:40https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html?highlight=scatter#matplotlib.pyplot.scatter -
matplotlib.pyplot.
2018-06-14 14:20:26完整说明https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot show的图是以目前数组max为最亮,min为最暗 -
matplotlib.pyplot.subplots_adjust
2019-03-29 01:18:13matplotlib.pyplot.subplots_adjust -
python中matplotlib.pyplot使用简介
2018-02-27 20:13:11pyplot介绍matplotlib.pyplot是一个有命令风格的函数集合,它看起来和MATLAB很相似。每一个pyplot函数都使一副图像做出些许改变,例如创建一幅图,在图中创建一个绘图区域,在绘图区域中添加一条线等等。在... -
python matplotlib.pyplot报错_import matplotlib.pyplot时报错
2020-11-29 22:31:59今天在import matplotlib.pyplot时报错:Traceback (most recent call last):File "C:\Users\lenovo\Desktop\zq.py", line 5, in import matplotlib.pyplotFile "C:\Python34\lib\site-packages\matplotlib\__init__... -
matplotlib.pyplot.bar
2019-06-16 16:57:34matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align=‘center’, data=None, **kwargs) x : 定义柱状图的x轴 height : 定义柱高 width : 定义柱宽(默认值为0.8) bottom : 可以是标量,也可以是列... -
matplotlib.pyplot.axis()与matplotlib.pyplot.axes()结构及用法
2019-05-06 18:01:07matplotlib.pyplot.axis() 官方文档 matplotlib.pyplot.axis(*v, **kwargs) 获得或设定axis内容的便利方法。 常用参数: xmin, ymin, xmax, ymax : float, optional The axis limits to be set. Either none or ...
-
信息安全风险评估与风险管理.ppt
-
java注解和反射的个人学习笔记
-
2021年 系统分析师 系列课
-
伊顿穆勒.rar电气设备选型资料大全 (适合刚刚入行的电气工程师对设备进行选型规划)详解 报价
-
信息安全管理与信息安全体系实践.ppt
-
2021春季学期-创新设计与实践-Lesson3
-
Leetcode 1775. Equal Sum Arrays With Minimum Number of Operations 数学方法,ceil向上取整
-
PPT大神之路高清教程
-
基于springboot实现表单重复提交.docx
-
MySQL 多实例安装 及配置主从复制实验环境
-
Flask-Restful笔记
-
Codeforces Round #704 (Div. 2) A-D题解
-
RDD基本操作
-
Windows系统管理
-
linux c spi应用层 通信源代码
-
Mycat 实现 MySQL的分库分表、读写分离、主从切换
-
opencv轮廓特征值 滚动条控制阈值参数
-
Vue项目城市选择页-列表性能优化(8-7)
-
牛牛量化策略交易
-
数据结构实践准备