【2.6.7】折线图(matplotlib-plot)及线条

在交互环境中查看帮助文档:

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='-')

一、plot用法示例

示例一

import matplotlib.pyplot as plt 
y1=[10,13,5,40,30,60,70,12,55,25] 
x1=range(0,10) 
x2=range(0,10) 
y2=[5,8,0,30,20,40,50,10,40,15] 

plt.plot(x1,y1,label='Frist line',linewidth=3,color='r',marker='o', 
markerfacecolor='blue',markersize=12) 
plt.plot(x2,y2,label='second line') 

plt.xlabel('Plot Number') 
plt.ylabel('Important var') 
plt.title('Interesting Graph\nCheck it out') 

plt.legend() 
plt.show() 

示例二

代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines

class HighlightSelected(lines.VertexSelector):
    def __init__(self, line, fmt='ro', **kwargs):
        lines.VertexSelector.__init__(self, line)
        self.markers, = self.axes.plot([], [], fmt, **kwargs)

    def process_selected(self, ind, xs, ys):
        self.markers.set_data(xs, ys)
        self.canvas.draw()

fig = plt.figure()
ax = fig.add_subplot(111)
x, y = np.random.rand(2, 30)
line, = ax.plot(x, y, 'bs-', picker=5)

selector = HighlightSelected(line)
plt.show()

图:

二、参数说明

2.1 linestyle可选参数

'-'       solid line style
'--'      dashed line style
'-.'      dash-dot line style
':'       dotted line style

2.2 marker可选参数

'.'       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	

2.3 color可用的颜色

对关键字参数color赋十六进制的RGB字符串如 color='#900302'

=============    ===============================
character        color
=============    ===============================
``'b'``          blue 蓝
``'g'``          green 绿
``'r'``          red 红
``'c'``          cyan 蓝绿
``'m'``          magenta 洋红
``'y'``          yellow 黄
``'k'``          black 黑
``'w'``          white 白

参考资料

个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn