matplotlib:颜⾊、标记和线类型,刻度、标签和图例,注释与⼦图加⼯,将图
⽚保存到⽂。。。
1.2 颜⾊、标记和线类型
matplotblib 的主函数 plot 接收带有x and y 轴的数组以及⼀些可选的字符串缩写参数来指名颜⾊和线类型。例如要⽤绿⾊括折号绘制 x 对 y 的线:ax.plot(x,y,'g--') 或者 ax.plot(x,y,linestyle='--',colur='g')
很多颜⾊缩写被⽤于常⽤颜⾊,可以指定⼗六进制的颜⾊代码(#CECECE)。
参考plot函数的⽂档查看所有线类型(jupyter 中使⽤plot?)
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
折线图还可以⼜标记来凸显实际的数据点,matplotlib 创建⼀个连续的折线图,插⼊点之间有时分辨不出。标记可以是样式字符串的⼀部分,样式字符串中的线类型,标记类型必须在颜⾊后⾯。
plot(np.random.randn(30).cumsum(),color='r',linestyle='dashed',marker='s') 更加显式的代码
后续的点默认式线性内插的。。。通过drawstyle 选项来更改
。。。。讲究。。。。。
由于我们像plot 传递来 label ,我们可使⽤plt.legend 为每条线⽣成⼀个⽤于区分的图例。(⽆论是否⼜label选项都要调⽤plt.legend 来⽣成图例。)
1.3 刻度、标签和图例
对于⼤多数图标修饰⼯作,有两种主要⽅式,使⽤程序性的pyplot 接⼝ 和更多⾯向独享的原⽣ matplotlib API。
pyplot 接⼝设计为交互式使⽤,包含了 xlim, xticks 和 xticklabels 等⽅法。这些⽅法分别控制了绘图范围,刻度位置以及刻度标签。
在没有函数参数的情况下调⽤,返回当前的参数值(例如 plt.xlim() 返回当前的x 轴绘图范围)
传⼊参数的情况下调⽤,例如:plt.xlim([0,10]) 会将x 轴的范围设置为0 到10.
这些⽅法都会在当前活动的回落最近创建的 AxesSubplot 上⽣效,这些⽅法的每⼀个对应于⼦图⾃⾝的两个⽅法,⽐如 xlim 对应于ax.get_lim and ax.set_lim 。好像使⽤ subplot 的⽅法更加显式,,,,(使⽤subplot_kw参数,就是add_subplot的参数)
add_subplot参数(部
分)
含义
projection ⼦图的投影类型{None, ‘aitoff’, ‘hammer’, ‘lambert’, ‘mollweide’, ‘polar’, ‘rectilinear’, str},。。应该就
是⼦图的类型,
polar等于 projection=‘polar’
alpha透明度facecolor fc颜⾊,轴⾯/轴的颜⾊labe xlabel ylabell标签
title标题
xlim ylim设置x轴视图限制。(bottom: float, top: float) xticklabels yticklabels刻度标签,列表xticks yticks刻度,列表
1.3.1 设置标题,轴标签,刻度和刻度标签
修改y 轴坐标是相同的过程,将上⾯的x 替换成 y 就⾏,轴的类型有⼀个 set ⽅法,可以批量设置绘图属性。
感觉⽤上subplots 不如在外⾯设置,在外⾯使⽤函数,功能还能多⼀些。
1.3.2 添加图例
图例是⽤来区分绘图元素。最简单的⽅式是在添加每个图表时传递label 参数。
legend ⽅法多了个loc 的位置参数。告诉在哪⾥放置图表,best 会⾃动选择适合的位置(尽量少的重叠图像),如果要取消图例中的元素,不要传⼊ label 或 label = ‘_nolegend_’
Location String  Location Code
===============  =============
'best'            0
'upper right'    1
'upper left'      2
'lower left'      3
'lower right'    4
'right'          5
'center left'    6
'center right'    7
'lower center'    8
'upper center'    9
'center'          10
===============  =============
bbox_to_anchor 与loc⼀起⽤于定位图例的框(x, y, width, height)or(x,y)
ncol  图例的列数,默认1
fontsize  nt或float 图例字体⼤⼩。
shadow  None or bool 阴影
framealpha  背景的不透明度
facecolor  背景⾊
title/title_fontsize
1.4 注释与⼦图加⼯
在图表上绘制⾃⼰的注释,⽽且注释中可能包含⽂本,箭头以及其他图形。你可以使⽤ text arrow annote ⽅法来添加注释和⽂本。
text 在图表上给定的坐标 (x,y) 根据可选的定制样式绘制⽂本。as.text(x,y,'hello world',family='monospace',fontsize=10)
绘制标普500指数从2007年以来的收盘价,并在图表中标注从2008到2009年⾦融危机的重要⽇期(阿巴阿巴阿巴阿巴)
还没见过 asof这个函数。。。DataFrame/Series.asof(where, subset=None)
返回where之前没有nan 的最后⼀⾏。subset, 对于dataframe ,使⽤指定的列来检查nan。
如果没有对应的值就返回nan。
>>> s = pd.Series([1,2, np.nan,4], index=[10,20,30,40])
>>> s
10  1.0
20  2.0
30    NaN
40  4.0
dtype: float64
>>> s.asof(20)# 获得索引20 的值
2.0
>>> s.asof([5,20])# 对于多个,第⼀个没有返回nan,
5    NaN
20  2.0
dtype: float64
>>> s.asof(30)# 这个是nan,就返回之前不是nan 的最后⼀⾏。
2.0
df = pd.DataFrame({'a':[10,20,30,40,50],'b':[None,None,None,None,500]},index=[1,2,3,4,5])
df.asof([3.5,4.5])# 考虑所有⾏的话,要都不是nan 的,
a b
3.5 NaN NaN
4.5 NaN NaN
df.asof([3.5,4.5],subset=['a'])
a    b                # 这⾥只考虑 a
3.530.0 NaN
4.540.0 NaN
from datetime import datetime
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ad_table('spx.csv',sep='\t',header=None,parse_dates=True,index_col=0)
spx=data['spx']
spx.plot(ax=ax,style='k-')
crisis_data =[
(datetime(2007,10,11),'Peak of bull market'),
(datetime(2008,3,12),'Bear Stearns Fails'),
(datetime(2008,9,15),'Lehman Bankruptcy')
]
for date,label in crisis_data:# ax.annotate⽅法在指定的x和y 坐标上绘制标签
ax.annotate(label,xy=(date,spx.asof(date)+75),xytext=(date,spx.asof(date)+225),arrowprops=dict(facecolor='black',                                    headwidth=4,width=2,headlength=4),horizontalalignment='left',verticalalignment='top') # 话说这位置,箭头宽度的参数的选择有什么⽅法吗。。。。
# 放⼤2007年到 2010年
ax.set_xlim(['1/1/2007','1/1/2011'])# ['2007-1-1', '2011-1-1'] 这样也⾏的,所有为啥要那么写
ax.set_ylim([600,1800])# 使⽤这两个⽅法⼿动设置图标的边界,⽽不是使⽤matplotlib的默认设置。
ax.set_title('Important dates in the 2008-2009 financial crisis')
annotate(s,xy, args,* kwargs)** , ⽤⽂本text 注释点xy。
xytext 放置⽂本的位置(x,y)。如果为None,则默认为xy。
xycoords 给出xy的坐标系。
textcoords xytext 的坐标系
arrowprops dict 在位置xy和xytext之间绘制箭头的属性
matplotlib中subplotcomment_clip bool或⽆ 当注释点xy在轴区域之外时是否绘制注释。
**kwargs 传递给Text 的参数。。禁⽌套娃,,⼜是⼀⽚参数被恶⼼到了。。。