matplotlib绘图的基本操作
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
matplotlib绘图的基本操作
plt.plot(x,y , fmt) :绘制坐标图
plt.boxplot(data, notch, position): 绘制箱形图
plt.bar(left, height, width, bottom) : 绘制条形图
plt.barh(width, bottom, left, height) : 绘制横向条形图
plt.polar(theta, r) : 绘制极坐标图
plt.pie(data, explode) : 绘制饼图
plt.scatter(x, y) :绘制散点图
plt.hist(x, bings, normed) : 绘制直⽅图
绘制图表的⼀些基本操作:
tips:如果你向plot()指令提供了⼀维的数组或列表,那么matplotlib将默认它是⼀系列的y值,并⾃动为你⽣成x的值,默认的x向量从0开始并且具有和y同样的长度。
"""matplotlib绘图的基本操作"""
import matplotlib.pyplot as plt
import numpy as np
# 绘制普通图像
x = np.linspace(-2*np.pi, 2*np.pi, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.cos(2*x)
# 创建figure对象,⽣成画板 # 参数依次是图名,⼤⼩,dpi,背景⾊,边缘⾊
plt.figure(num='正余弦函数图', figsize=(10, 6), dpi=120, facecolor='y', edgecolor='g')
# 在绘制时设置lable, 逗号是必须的
l1 = plt.plot(x, y1, color='red', linestyle='-', linewidth=0.5, label='$sin(x)$')
l2 = plt.plot(x, y2, 'b', label='$cos(x)$')
# plt.plot(x, y1, 'r--', x, y2, 'b-.', x, y3, 'g') 叠加图在⼀个图画出多条不同格式的线
# 设置坐标轴的取值范围
plt.axis((-6.5, 6.5, -1.1, 1.1))
# plt.xlim((-6.5, 6.5))
# plt.ylim((-1.1, 1.1))
# 设置坐标轴的lable
plt.xlabel('X axis')
plt.ylabel('Y axis')
# 设置x坐标轴刻度, 原来为0.25, 修改后为0.5 # plt.xticks(np.linspace(-2*np.pi, 2*np.pi, 9))
# 第⼀个参数是位置,第⼆个参数是标签lable,$使字体倾斜,\ 输出空格,\alpha_i输出数学符号α1也可直接alpha
plt.xticks((-2*np.pi, -3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi),
('$-2π$', '$-3π/2$', '$-π$', '$-π/2$', r'$0\ \alpha_i$', 'π/2', 'π', '3π/2', '2π'))
plt.yticks((-1, 0, 1))
# 设置、显⽰legend
plt.legend(loc='best') # loc参数设置图例显⽰的位置
# 设置图表的标题
plt.title('cos&sin')
plt.text(-np.pi, 1, '任意位置添加⽂字',fontdict={'size': 10, 'color': 'y'}) # text在图中任意位置添加⽂字,前两个参数是左下⾓的位置坐标
plt.annotate('max', xy=(0, 1), xytext=(1, 1.05), arrowprops=dict(facecolor='k', shrink=1)) # 注释的地⽅xy(x,y)和插⼊⽂本的地⽅xytext(x1,y1) # 移动坐标轴,spines为脊梁,即4个边框
ax = plt.gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none') # 设置右‘脊梁’为⽆⾊
ax.spines['top'].set_color('none') # 设置上‘脊梁’为⽆⾊
ax.xaxis.set_ticks_position('bottom') # 底部‘脊梁’设置为X轴
ax.spines['bottom'].set_position(('data', 0)) # 底部‘脊梁’移动位置,y的data
ax.yaxis.set_ticks_position('left') # 左部‘脊梁’设置为Y轴
ax.spines['left'].set_position(('data', 0)) # 左部‘脊梁’移动位置,x的data
# 给特殊点做注释,在2π/3的位置给两条函数曲线加⼀个注释
plt.plot([2*np.pi/3, 2*np.pi/3], [0, np.sin(2*np.pi/3)], 'r--') # xy是基于xycoords的data
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(2*np.pi/3, np.sin(2*np.pi/3)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=.2")) # +10,+30表⽰基于xy加10,加30,textcoords='offset points'代表基于xy
plt.scatter([2*np.pi/3], [np.sin(2*np.pi/3)], 40, 'r') # 绘制点x,y,⼤⼩,颜⾊
plt.plot([2*np.pi/3, 2*np.pi/3], [0, np.cos(2*np.pi/3)], 'b--')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(2*np.pi/3, np.cos(2*np.pi/3)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=.2")) # arrowprops设置指⽰线的格式,connectionstyle设置线的⾓度,弧度
plt.scatter([2*np.pi/3], [np.cos(2*np.pi/3)], 40, 'b')
plt.show()
线条风格linestyle描述
'-'实线':'虚线
'--'破折线'None', ' ', ''什么都不画
'-.'点划线
线条标记maker描述
'o'圆圈'.'点
'D'菱形's'正⽅形
'h'六边形1'*'星号
'H'六边形2'd'⼩菱形
'_'⽔平线'v'⼀⾓朝下的三⾓形
'8'⼋边形'<'⼀⾓朝左的三⾓形
'p'五边形'>'⼀⾓朝右的三⾓形
','像素'^'⼀⾓朝上的三⾓形
'+'加号'\’竖线
'None','',' '⽆'x'X
颜⾊
可以通过调⽤matplotlib.pyplot.colors()得到matplotlib⽀持的所有颜⾊。
别名颜⾊别名颜⾊
b蓝⾊g绿⾊
r红⾊y黄⾊
c青⾊k⿊⾊
m洋红⾊w⽩⾊
如果这两种颜⾊不够⽤,还可以通过两种其他⽅式来定义颜⾊值:
使⽤HTML⼗六进制字符串 color='eeefff' 使⽤合法的HTML颜⾊名字('red','chartreuse'等)。
也可以传⼊⼀个归⼀化到[0,1]的RGB元祖。
color=(0.3,0.3,0.4)
很多⽅法可以介绍颜⾊参数,如title()。
plt.tilte('Title in a custom color',color='#123456')
背景⾊
通过向如matplotlib.pyplot.axes()或者matplotlib.pyplot.subplot()这样的⽅法提供⼀个axisbg参数,可以指定坐标这的背景⾊。
subplot(111,axisbg=(0.1843,0.3098,0.3098)
(1)title常⽤参数
fontsize设置字体⼤⼩,默认12,可选参数 ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
fontweight设置字体粗细,可选参数 ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
fontstyle设置字体类型,可选参数[ 'normal' | 'italic' | 'oblique' ],italic斜体,oblique倾斜
verticalalignment设置⽔平对齐⽅式,可选参数: 'center' , 'top' , 'bottom' ,'baseline'
horizontalalignment设置垂直对齐⽅式,可选参数:left,right,center
rotation(旋转⾓度)可选参数为:vertical,horizontal 也可以为数字
alpha透明度,参数值0⾄1之间
backgroundcolor标题背景颜⾊
bbox给标题增加外框,常⽤参数如下:
boxstyle⽅框外形
facecolor(简写fc)背景颜⾊
edgecolor(简写ec)边框线条颜⾊
edgewidth边框线条⼤⼩
(2)title例⼦
plt.title('Interesting Graph',fontsize='large',fontweight='bold') 设置字体⼤⼩与格式
plt.title('Interesting Graph',color='blue') 设置字体颜⾊
plt.title('Interesting Graph',loc ='left') 设置字体位置
plt.title('Interesting Graph',verticalalignment='bottom') 设置垂直对齐⽅式
plt.title('Interesting Graph',rotation=45) 设置字体旋转⾓度
plt.title('Interesting',bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 )) 标题边框
⾯向对象api例⼦:
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[3,6,7,9,2]
fig,ax=plt.subplots(1,1)
ax.plot(x,y,label='trend')
ax.set_title('title test',fontsize=12,color='r')
plt.show()</span>
plt.annotate()⽂本注释
在数据可视化的过程中,图⽚中的⽂字经常被⽤来注释图中的⼀些特征。
使⽤annotate()⽅法可以很⽅便地添加此类注释。
在使⽤annotate时,要考虑两个点的坐标:被注释的地⽅xy(x, y)和插⼊⽂本的地⽅xytext(x, y),见以上程序。
(1)annotate语法说明:annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)
s 为注释⽂本内容
xy 为被注释的坐标点
xytext 为注释⽂字的坐标位置
xycoords 参数如下:
figure points points from the lower left of the figure 点在图左下⽅
figure pixels pixels from the lower left of the figure 图左下⾓的像素
figure fraction fraction of figure from lower left 左下⾓数字部分
axes points points from lower left corner of axes 从左下⾓点的坐标
axes pixels pixels from lower left corner of axes 从左下⾓的像素坐标
axes fraction fraction of axes from lower left 左下⾓部分
data use the coordinate system of the object being annotated(default) 使⽤的坐标系统被注释的对象(默认)
polar(theta,r) if not native ‘data’ coordinates t
extcoords 设置注释⽂字偏移量
| 参数 | 坐标系 |
| 'figure points' | 距离图形左下⾓的点数量 |
| 'figure pixels' | 距离图形左下⾓的像素数量 |
| 'figure fraction' | 0,0 是图形左下⾓,1,1 是右上⾓ |
| 'axes points' | 距离轴域左下⾓的点数量 |
| 'axes pixels' | 距离轴域左下⾓的像素数量 |
| 'axes fraction' | 0,0 是轴域左下⾓,1,1 是右上⾓ |
| 'data' | 使⽤轴域数据坐标系 |
arrowprops #箭头参数,参数类型为字典dict
width the width of the arrow in points 点箭头的宽度
headwidth the width of the base of the arrow head in points 在点的箭头底座的宽度
headlength the length of the arrow head in points 点箭头的长度
shrink fraction of total length to ‘shrink’ from both ends 总长度为分数“缩⽔”从两端
facecolor 箭头颜⾊
bbox给标题增加外框,常⽤参数如下:
boxstyle⽅框外形
facecolor(简写fc)背景颜⾊
edgecolor(简写ec)边框线条颜⾊
edgewidth边框线条⼤⼩
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc为facecolor,ec为edgecolor,lw为lineweight
(2)案例
1. import matplotlib.pyplot as plt
2. import numpy as np
3. x = np.arange(0, 6)
4. y = x * x
5. plt.plot(x, y, marker='o')
6. for xy in zip(x, y):
7. plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points')
8. plt.show()
1. <span style="font-size:14px;">plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05))</span>
移动坐标系(Spines)
Spines 是连接轴刻度标记的线,是轴的边界,⽽且标明了数据区域的边界,可以被放置在任意位置。
我们想要spines 置于中间。
因为有四个spine(上下左右),我们将要通过设置颜⾊(⽆)丢弃上⾯和右侧的部分,进⽽移动下⾯和左边的线到坐标0(数据空间)。
代码见上
text设置⽂字说明
(1)text语法说明
text(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")
x,y:表⽰坐标值上的值
string:表⽰说明⽂字
fontsize:表⽰字体⼤⼩
verticalalignment:垂直对齐⽅式,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
horizontalalignment:⽔平对齐⽅式,参数:[ ‘center’ | ‘right’ | ‘left’ ]
xycoords选择指定的坐标轴系统:
figure points points from the lower left of the figure 点在图左下⽅
figure pixels pixels from the lower left of the figure 图左下⾓的像素
figure fraction fraction of figure from lower left 左下⾓数字部分
axes points points from lower left corner of axes 从左下⾓点的坐标
axes pixels pixels from lower left corner of axes 从左下⾓的像素坐标
axes fraction fraction of axes from lower left 左下⾓部分
data use the coordinate system of the object being annotated(default) 使⽤的坐标系统被注释的对象(默认)
polar(theta,r) if not native ‘data’ coordinates t
arrowprops #箭头参数,参数类型为字典dict
width the width of the arrow in points 点箭头的宽度
headwidth the width of the base of the arrow head in points 在点的箭头底座的宽度
headlength the length of the arrow head in points 点箭头的长度
shrink fraction of total length to ‘shrink’ from both ends 总长度为分数“缩⽔”从两端
facecolor 箭头颜⾊
bbox给标题增加外框,常⽤参数如下:
boxstyle⽅框外形
facecolor(简写fc)背景颜⾊
edgecolor(简写ec)边框线条颜⾊
edgewidth边框线条⼤⼩
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc为facecolor,ec为edgecolor,lw为lineweight
(2)案例
⽂字格式与位置:
1. import matplotlib.pyplot as plt
2. fig = plt.figure()
3. plt.axis([0, 10, 0, 10])
4. t = "This is a really long string that I'd rather have wrapped so that it"\
5. " doesn't go outside of the figure, but if it's long enough it will go"\
6. " off the top or bottom!"
7. plt.text(4, 1, t, ha='left', rotation=15, wrap=True)
8. plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
9. plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)
10. plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',va='top',wrap=True)
11. plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
12. plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)
13. plt.show()
花式⽂本框:
1. import matplotlib.pyplot as plt
2. plt.text(0.6, 0.5, "test", size=50, rotation=30.,ha="center", va="center",bbox=dict(boxstyle="round",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))
3. plt.text(0.5, 0.4, "test", size=50, rotation=-30.,ha="right", va="top",bbox=dict(boxstyle="square",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))
4. plt.draw()
5. plt.show()
数学公式:
1. plt.title(r'αi>βi', fontsize=20)
2. plt.text(1, -0.6, r'∑∞i=0x i', fontsize=20)
3. plt.text(0.6, 0.6, r'Asin(2ωt)',fontsize=20)
Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js。