python3.6.5 + matplotlib2.0.0 常用函数笔记

长时间没有再使用matplotlib,最近又拿出来简单看了一遍,不过在安装的时候发现安装完成后运行时出现的界面和以往的不一样。主要有以下不同:

  1. 在新版本pycharm中使用时,运行的plot会自动出现在ide的窗口里,不是很方便,如果不喜欢可以在file->settings->tools->Python Scientific->show plots in tool window 前面的勾选框不勾选即可。
  2. 最新版matplotlib,好像是2.2.几还是2.3,在使用时窗口发生了很大的变化,好多按钮不见了,所以我还是安装了2.0.0,pip install matplotlib==2 即可。

好,现在开始正式记录常用的一些函数,方便使用时查询。

import matplotlib.pyplot as plt

  • 设置在坐标轴在最中间(其他位置同理)

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(-3,3,100)

y = x

plt.plot(x,y)

plt.xlim(-3,3)

ax = plt.gca()

ax.spines['top'].set_color('None')

ax.spines['right'].set_color('None')

ax.xaxis.set_ticks_position('bottom')

ax.spines['bottom'].set_position(('data',0))

ax.yaxis.set_ticks_position('left')

ax.spines['left'].set_position(('data',0))

plt.show()

  • 最基本的画线(平滑的曲线)

plt.plot(x_data,y_data)   #可以只指定两个点,那就是简单的画直线

  • 标题

plt.title('my title')

  • 设置曲线的颜色和style

plt.plot(x,y,color='black',linewidth=2,linestyle='--')

  • 显示初始时的x轴和y轴的上下限

plt.xlim((-3,3))     plt.ylim((-1,4))

  • 设置x轴和y轴的标签

plt.xlabel('i am x')  plt.ylabel('i am y')

  • 设置x轴和y轴的坐标

new_ticks = np.linspace(-5,5,15)

plt.xticks(new_ticks)

plt.yticks([-2,-1,0,1,2],['too bad','bad','normal','good','really good'])

  • 设置坐标轴不可见

ax = plt.gca()

ax.spines['top'].set_color('none')

  • 设置坐标轴的位置

ax.spines['bottom'].set_position(('data',1))  # 下部轴显示在纵轴数据为1的地方(即下部轴为y=1直线)

  • 设置图例(legend)

plt.plot(x,y1,label='first')

plt.plot(x,y2,label='second')

plt.legend()     #默认就是loc=‘best’,会自动寻找较空的位置放图例

# plt.legend(loc='lower left / upper right / best')

  • 设置注解(annotation)两种方式

plt.annotate('hello annotate',xy=(x0,y0),xycoords='data',xytext=(30,-30),textcoords = 'offset points',
             fontsize=12,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.5'))

plt.text(-1,-4,r'$this\ is\ text\ \alpha_2\ \sigma\ \mu$',
         fontdict={'size':16,'color':'r'})

  • 散点图

plt.scatter(x_data,y_data,marker=,color=,alpha=)

  • 去掉ticks(坐标轴上数字等)

plt.xticks(())

柱状图

plt.bar(x,+y1,facecolor='red',edgecolor='white')

plt.bar(x,-y2,facecolor='blue',edgecolor='white')   # -y2表示显示在横坐标下方

for x0,y0 in zip(x,y1):

    plt.text(x0,y0+0.005,'%.2f'%y0,ha='center',va='bottom') # ha表示水平对齐

for x0,y0 in zip(x,y2):

    plt.text(x0,-y0-0.005,'%.2f'%y0,ha='center',va='top')

  • 等高线

X,Y = np.meshgrid(x,y)

plt.contourf(X,Y,Z,8,alpha=0.75,cmap=plt.cm.hot)    #Z代表高度,8代表有9个分界线,cmap为颜色对应

C = plt.contour(X,Y,Z,8,linewidth=1,colors='black')

plt.clabel(C,inline=True,fontsize=10)

  • 3D图

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = Axes3D(fig)

X = np.arange(-4,4,0.2)

Y = np.arange(-4,4,0.2)

X,Y = np.meshgrid(X,Y)

R = np.sqrt(X**2+Y**2)

Z = np.sin(R)

ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.cm.rainbow)

ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap=plt.cm.rainbow)

  • 子图

ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1) # 总的分3行3列,从(0,0)开始

ax1.set_title('subplot 1')   # 注意此时的设置都要使用set_xxx函数不能直接用title()

ax2 = plt.subplot2grid((3,3),(1,0),colspan=1,rowspan=1)

ax2.plot([0,1],[0,3])

 

 

只记录以上常用函数,更多函数使用可以查看莫烦python关于matplotlib的教程(bilibili是个学习网站)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
python上使用的绘图库matplotlibV2.0英文官方版本. User’s Guide Introduction Installing Tutorials Working with text Colors Customizing matplotlib Interactive plots Selected Examples What’s new in matplotlib GitHub Stats License Credits The Matplotlib API Plotting commands summary API Changes The top level matplotlib module afm (Adobe Font Metrics interface) animation module artist Module Axes class axis and tick API backends cbook cm (colormap) collections colorbar colors dates dviread figure finance font_manager gridspec image legend and legend_handler lines markers mathtext mlab offsetbox patches path patheffects projections pyplot rcsetup sankey scale spines style text ticker tight_layout Working with transformations triangular grids type1font units widgets The Matplotlib FAQ Installation Usage How-To Troubleshooting Environment Variables Working with Matplotlib in Virtual environments Working with Matplotlib on OSX Toolkits Mapping Toolkits General Toolkits High-Level Plotting External Resources Books, Chapters and Articles Videos Tutorials The Matplotlib Developers’ Guide Contributing Developer’s tips for testing Developer’s tips for documenting matplotlib Developer’s guide for creating scales and transformations Developer’s tips for writing code for Python 2 and 3 Working with matplotlib source code Reviewers guideline Release Guide Matplotlib Enhancement Proposals Matplotlib Examples animation Examples api Examples axes_grid Examples color Examples event_handling Examples frontpage Examples images_contours_and_fields Examples lines_bars_and_markers Examples misc Examples mplot3d Examples pie_and_polar_charts Examples pylab_examples Examples pyplots Examples scales Examples shapes_and_collections Examples showcase Examples specialty_plots Examples statistics Examples style_sheets Examples subplots_axes_and_figures Examples tests Examples text_labels_and_annotations Examples ticks_and_spines Examples units Examples user_interfaces Examples widgets Examples Glossary Index Module Index Search Page
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值