python可视化之matplotlib

利用matplotlib绘图基本流程:

  1. 导入相关包
    import matplotlib.pyplot as plt
    import numpy as np
    from numpy.random import randn
    1. 创建图表
      fig=plt.figure(…)
      axe1=fig.add_subplot(行,列,位置)
      axe2=fig.add_subplot(行,列,位置)
      axe3=fig.add_subplot(行,列,位置)
      ….
      3.绘图
      plt.plot/scatter/hist(….) (注:这种是直接在最后用过的一个subplot绘图,例如最后创建的axe3上画图)
      又或者
      axe1.plot/scatter/hist(….)
      axe2.plot/scatter/hist(….)
      这就是指定的subplot上绘图
      plt.show()
      一种更简便的方法:
      fig,axe=plt.subplots(行,列,个数)
      这里的axe是一个数组,维度和参数对应
      然后可以对axe循环绘图(图形一样)

颜色、标记、线型

plot(x,y,color=,linestyle=,marker=,)中可以设置颜色、标记和线型。
或者不用直接合并表示,例如plot(x,y,’k–’)
其中的符号意思如下

颜色
线型
标记

代码 1

import  matplotlib.pyplot as plt
import  numpy as np
from numpy.random import randn
fig1=plt.figure()
axe11=fig1.add_subplot(2,2,1)
axe12=fig1.add_subplot(2,2,2)
axe13=fig1.add_subplot(2,2,3)
axe14=fig1.add_subplot(2,2,4)
axe11.plot(randn(50).cumsum(),linestyle='--',color='g',marker='o')
axe12.hist(randn(50),bins=20,linestyle='-',color='y')
axe13.scatter(np.arange(30),np.arange(30)+9,color='r')
axe14.plot(randn(50),'c:',marker='+')
plt.subplots_adjust(wspace=0,hspace=0)
plt.show()

效果图1:

效果图

添加坐标轴、轴标题、图表标题、图例

代码2

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
# 通过ax.set_xtickls()设置横坐标刻度值位置,对应修改为y就可设置纵坐标刻度值位置
ticks=ax.set_xticks([0,10,20,30,40,50])

# 默认之前设置的刻度值位置就为刻度值表示,也可以通过ax.set_xticklabels()设置自己想要的刻度值表示形式;纵坐标也是
xlabel=ax.set_xticklabels(['one','two','three','four','five','six'])

# 通过ax.set_xlabel()设置横坐标标题/set_ylabel()设置纵坐标标题
ax.set_xlabel('This is xticklabel')
ax.set_ylabel('This is yticklabel')

# 通过ax.set_title()设置图表标题
ax.set_title('I am the title of the graph')

#通过在plot()中设置参数‘label=’即可为该数据设置图例;如果图例不需要某一个图例,在plot()中不设置参数label或者设置label='_nolegend_'
ax.plot(randn(50).cumsum(),'r--',marker='+',label='firstPic')
ax.plot(randn(50).cumsum(),'y-',marker='o',label='secondPic')
ax.plot(randn(50).cumsum(),'g-.',marker='h',label='thirdPic')

ax.legend(loc='best')#设置图例及其放置位置,对应的还有
plt.show()

效果图2

插入坐标轴、标题和图例
未完待续…..

猜你喜欢

转载自blog.csdn.net/brave_jcc/article/details/80909137