一、颜色、标记(marker)和线型
matplotlib的plot函数接受一组X和Y坐标,还可以接受一个表示颜色和线型的字符串缩写。例如要根据xy绘制绿色虚线,代码如下:
import matplotlib.pyplot as plt
x=[1,2,3]
y=[5,7,4]
plt.plot(x,y,'g--') # plt.plot(x,y,linestyle='--',color='g')效果一样
plt.show()

完整的linestyle列表如下:
颜色:
========== ========
character color
========== ========
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
========== ========
标记:可以放入格式字符串中,但标记类型和线型必须放在颜色后面。
标记 | 描述 | 标记 | 描述 |
‘o’ | 圆圈 | ‘.’ | 点 |
‘D’ | 菱形 | ‘s’ | 正方形 |
‘h’ | 六边形1 | ‘*’ | 星号 |
‘H’ | 六边形2 | ‘d’ | 小菱形 |
‘_’ | 水平线 | ‘v’ | 一角朝下的三角形 |
‘8’ | 八边形 | ‘<’ | 一角朝左的三角形 |
‘P’ | 五边形 | ‘>’ | 一角朝右的三角形 |
‘,’ | 像素 | ‘^’ | 一角朝上的三角形 |
‘+’ | 加号 | ‘\’ | 竖线 |
‘None’ | 无 | ‘x’ | x |
- 实线
-- 短线
-. 短点相间线
: 虚点线
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.random.randn(30).cumsum(),'mx--') # plt.plot(np.random.randn(30).cumsum(),color='m',linestyle='--',marker='x')
plt.show()
二、刻度、标签和图例
1.设置标题、轴标签、刻度及刻度标签
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure();ax=fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum())
plt.show()
修改x轴的刻度:set_xticks,告诉matplotlib要将刻度放在数据范围中的哪些位置
set_xticklabels,将任何其他值作为标签
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure();ax=fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum())
#修改x刻度
ticks=ax.set_xticks([0,250,500,750,1000])
labels=ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small')
#设置标题
ax.set_title('alulu')
#设置x轴名称
ax.set_xlabel('stages')
plt.show()
2.添加图例(legend)
方式一:在添加subplot的时候传入label参数
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure();ax=fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum(),'k',label='one')
ax.plot(np.random.randn(1000).cumsum(),'m--',label='two')
ax.plot(np.random.randn(1000).cumsum(),'b.',label='three')
ax.legend(loc='best') #plt.legend() 自动创建图例 loc告诉matplotlib图例放在哪
plt.show()

111