高效使用Matplotlib || 原文总结及资料补充

原文,第三方翻译,及代码github

Effectively Using Matplotlib

高效使用 Python 可视化工具 Matplotlib

pbpython/Effectively-Using-Matplotlib.ipynb at master · chris1610/pbpython

文章概括总结

matplotlib的两种接口

matplotlib有两种接口。第一种是基于MATLAB并使用基于状态的接口。第二种是面向对象的接口。matplotlib的新用户应该学习使用面向对象的接口。

学习matplotlib的步骤

  1. 学习基本的matplotlib术语,尤其是什么是图和坐标轴
  2. 始终使用面向对象的接口,从一开始就养成使用它的习惯
  3. 用基础的pandas绘图开始你的可视化学习
  4. 用seaborn进行更复杂的统计可视化
  5. 用matplotlib来定制pandas或者seaborn可视化

matplotlib的术语理解图

术语理解.png

可用样式的查看和选择

plt.style.avaliable
plt.style.use('')

创建figure和ax:plt.subplots

可用参数

  • nrows
  • ncols
  • sharey
  • sharex
  • figsize

返回对象

  • figure对象
  • ax对象组成的numpy数组(如果nrows和ncols大于1的话,否则为一个ax对象)

更改和设置matplotlib的参数

  1. ax对象上调用set_xxx方法

    fig,ax= plt.subplots()
    top_10.plot(kind='barh',y="Sales",x="Name",ax=ax)
    ax.set_xlim([-10000,140000])
    ax.set_xlabel('Total Revenue')
    ax.set_ylabel('Customer');
    
    
  2. ax 调用set方法,方法参数指定xxx参数

    fig,ax= plt.subplots(figsize=(5,6))
    top_10.plot(kind='barh',y="Sales",x="Name",ax=ax)
    ax.set_xlim([-10000,140000])
    ax.set(title='2014 Revenue',xlabel='Total Revenue')
    ax.legend().set_visible(False)
    
    
  3. FuncFormatter调整数字格式

    def currency(x,pos):
      'The two args are the value and tick position'
      ifx>= 1000000:
        return'${:1.1f}M'.format(x*1e-6)
      return'${:1.0f}K'.format(x*1e-3)
    
    formatter= FuncFormatter(currency)
    # currency的两个参数调用时传入
    ax.xaxis.set_major_formatter(formatter)
    
    

注释的添加

  1. 垂直线:ax.axvline()
  2. 自定义文本:ax.text()

图像的输出

  • 查看可用的输出格式
fig.canvas.get_supported_filetypes()

  • 保存图像
fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")

汇总及图像理解

# Get the figure and the axes
fig,(ax0,ax1)= plt.subplots(nrows=1,ncols=2,sharey=True,figsize=(7,4))
top_10.plot(kind='barh',y="Sales",x="Name",ax=ax0)
ax0.set_xlim([-10000,140000])
ax0.set(title='Revenue',xlabel='Total Revenue',ylabel='Customers')
# Plot the average as a vertical line
avg= top_10['Sales'].mean()
ax0.axvline(x=avg,color='b',label='Average',linestyle='--',linewidth=1)
# Repeat for the unit plot
top_10.plot(kind='barh',y="Purchases",x="Name",ax=ax1)
avg= top_10['Purchases'].mean()
ax1.set(title='Units',xlabel='Total Units',ylabel='')
ax1.axvline(x=avg,color='b',label='Average',linestyle='--',linewidth=1)
# Title the figure
fig.suptitle('2014 Sales Analysis',fontsize=14,fontweight='bold');
# Hide the legends
ax1.legend().set_visible(False)
ax0.legend().set_visible(False)

案例图说明
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容