错误:
执行
import matplotlib.pyplot 报错
ImportError: No module named _tkinter, please install the python-tk package
解决方法:
sudo apt-get install python-tk
错误:
执行
import matplotlib.pyplot 报错
ImportError: No module named _tkinter, please install the python-tk package
解决方法:
sudo apt-get install python-tk
转载于:https://www.cnblogs.com/rabitvision/p/7508790.html
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是必须的,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()
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. |
更新……
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.
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()