- 元 素
- x轴和y轴
- 外文名
- Matplotlib
- 作 用
- 绘图
- 所属领域
- 计算机
- 中文名
- 绘图库
-
matplotlib
2019-04-20 19:19:46今天我们来介绍一下python的一个可视化工具matplotlib matplotlib 使用matplotlib的方式有很多,但最通常的是Pylab模式的ipython(-ipython –pylab) matplotlib的api都位于matplotlib.pyplot中,所以一般的引入方式...今天我们来介绍一下python的一个可视化工具matplotlib
matplotlib
使用matplotlib的方式有很多,但最通常的是Pylab模式的ipython(-ipython –pylab)
matplotlib的api都位于matplotlib.pyplot中,所以一般的引入方式为:
import matplotlib.pyplot as plt
Figure、Subplot
Figure
matplitlib的图像必须在Figure中,Figure创建方式如下:
fig = plt.figure() # 之后会弹出一个Figure窗口
创建好Figure后,并不能直接绘图,需要使用add_subplot创建一个或多个子图,在子图中绘图,创建方式如下:
ax1 = fig.add_subplot(2,2,1) # 将figure分为四块,在第一块创建一个子图;返回AxesSubplot对象
之后我们就可以绘制我们的图像了
plt.plot(randn(50).cumsum(), 'k--')
Figure和subplot的创建经常使用,所以matplotlib提供了简洁的创建方式:
fig, axes = plt.subplots(2,3) # 创建一个新Figure、并返回一个含有已创建subplot对象的Numpy数组 ax = axes[0,1] # 引用第一行第二列的subplot对象
该函数的一些参数选项:
调整图像之间的间距
通常情况下,matplotlib会在subplot外围留下一些边距,并在subplot之间留下一些间距。
我们可以利用subplots_adjust()函数来修改间距
subplots_adjust(left=None,bootom=None,right=None,top=None,wspace=None,hspace=None) # 该函数是一个顶级函数;wspace、hspace用来控制宽度和高度的百分比,用作subplot之间的间距 plt.subplots_adjust(wspace=0, hspace=0) # 设置subplots之间的间距为0
颜色、线型和标记
matplotlib的plot()函数接受一组X和Y坐标,和一个表示颜色和线形的字符串
ax.plot(x,y,'g--') # 根据x,y绘制绿色虚线 # ax为一subplot
刻度、标签和图例
设置X轴范围:
plt.xlim() # 返回当前X轴的范围 plt.xlim([0,10]) # 将X轴的范围设为[0, 10] # 以上方法都只对当前或最近创建的Subplot起作用
设置标题、轴标签、刻度以及刻度标签
-
设置标题
ax.set_title("My first matplotlib plot") # 设置对应dubplot的标题
-
设置轴标签
ax.set_xlabel() # 为对应subplot的x轴设置标签 ax.set_ylabel()
-
设置刻度
设置刻度有两个方法,set_xticks和set_xticklabels,前者告诉maatplotlib将刻度放在对应范围的哪个位置,默认情况下这些刻度就是刻度标签;后者可以将任何其他类型的值作为标签
ax.set_xticks([0,1,2,3,4]) # 将0,1,2,3,4作为x轴刻度标签 ax.set_xticklabels(['one','two','three','four','five']) # 将one,two,three,four,five作为x轴刻度标签 ax.set_yticks() ax.set_xticklabels()
添加图例
图例是标识图表元素的重要工具。
- 方式一,在添加subplot时传入label参数
fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(randn(1000).cumsum(), 'k--', label='one') ax.plot(randn(1000).cumsum(), 'k', label='two') ax.plot(randn(1000).cumsum(), 'k.', label='three') ax.legend(loc='best') # loc指定图例放置的位置,'best'参数标识系统将图例放置到最不碍事的地方
将图标保存到文件
利用plt.savefig可以将当前图表保存到文件
plt.savefig('figpath.png', dpi=400) # 将当前图表存储为png文件 # dpi参数指定每英寸点数(分辨率)
Pandas中的绘图函数
从上面的例子中我们可以看出,matplotlib实际上是一个比较低级的画图工具,当我们绘制一张图标时,往往要指定他的多个属性,如图例,标签,标题等。而pandas中的绘图函数大大简化了这个过程。
Series与DataFrame数据都可以通过调用plot函数来绘制图表
-
Series:
s = Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10)) s.plot()
-
DataFrame:
df = DataFrame(np.random.randn(10,4).cumsum(), columns=['A','B','C','D'],index=np.arange(0,100,10)) # columns参数指定图例名称,index指定x轴标签 # np.random.randn(10,4)共10行4列,产生四条曲线,每条曲线十个数据点 df.plot()
除了matplotlib外,还有许多优秀的画图工具,如chaco、mayavi等
目前对于matplotlib的介绍就是这些,更多的知识可以研究一下pandas官方文档(pandas正在不断地更新中,会提供越来越多的函数),链接如下:
http://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html
-
-
最简单的matplotlib安装教程
2019-03-05 19:59:42在网上看见许多matplotlib的安装教程都是比较复杂,需要配置许多环境,对于电脑基础不好的人来说可是一件头疼的事情,今天我介绍一个简单的安装方法。 1.Win+R输入cmd进入到CMD窗口下,执行python -m pip install -...在网上看见许多matplotlib的安装教程都是比较复杂,需要配置许多环境,对于电脑基础不好的人来说可是一件头疼的事情,今天我介绍一个简单的安装方法。
1.Win+R输入cmd进入到CMD窗口下,执行python -m pip install -U pip setuptools进行升级。
2.输入python -m pip install matplotlib进行自动的安装,系统会自动下载安装包
3.进入到python idle中,运行import matplotlib,如下图所示,如果没有报错,就证明安装成果。
输入以下代码运行成果证明安装没问题
import matplotlib.pyplot as plt labels='frogs','hogs','dogs','logs' sizes=15,20,45,10 colors='yellowgreen','gold','lightskyblue','lightcoral' explode=0,0.1,0,0 plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50) plt.axis('equal') plt.show()
-
python中的matplotlib用法
2016-11-10 23:11:23python中的matplotlib是一种用于创建图表的桌面绘图包(主要是2D方面)。 使用python对matplotlib库操作使得对图形的显现极为方便,下面是用的较多的一些用法。 建议配合Ipython使用,如果通过cmd启动ipython,请...这个
repo
用来记录一些python技巧、书籍、学习链接等,欢迎star
github地址
python中的matplotlib是一种用于创建图表的桌面绘图包(主要是2D方面)。
使用python对matplotlib库操作使得对图形的显现极为方便,下面是用的较多的一些用法。
建议配合Ipython使用,如果通过cmd启动ipython,请使用ipython --pylab启动,方便绘图时的即时操作修改与显示,如果用jupyter notebook,则可使用ipython的魔术操作%matploltlib inline,当然如果不用ipython的话最后为了让图形显示出来请键入:plt.show()
一、综合介绍
1、常规方法作柱形,散点,饼状,折线图
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline fig = plt.figure(figsize=(10,8)) #建立一个大小为10*8的画板 ax1 = fig.add_subplot(331) #在画板上添加3*3个画布,位置是第1个 ax2 = fig.add_subplot(3,3,2) ax3 = fig.add_subplot(3,3,3) ax4 = fig.add_subplot(334) ax5 = fig.add_subplot(3,3,5) ax6 = fig.add_subplot(3,3,6) ax7 = fig.add_subplot(3,3,7) ax8 = fig.add_subplot(3,3,8) ax9 = fig.add_subplot(3,3,9) ax1.plot(np.random.randn(10)) _ = ax2.scatter(np.random.randn(10),np.arange(10),color='r') #作散点图 ax3.hist(np.random.randn(20),bins=10,alpha=0.3) #作柱形图 ax4.bar(np.arange(10),np.random.randn(10)) #做直方图 ax5.pie(np.random.randint(1,15,5),explode=[0,0,0.2,0,0]) #作饼形图 x = np.arange(10) y = np.random.randn(10) ax6.plot(x,y,color='green') ax6.bar(x,y,color='k') data = DataFrame(np.random.randn(1000,10), columns=['one','two','three','four','five','six','seven','eight','nine','ten']) data2 = DataFrame(np.random.randint(0,20,(10,2)),columns=['a','b']) data.plot(x='one',y='two',kind='scatter',ax=ax7) #针对DataFrame的一些作图 data2.plot(x='a',y='b',kind='bar',ax=ax8,color='red',legend=False) data2.plot(x='a',y='b',kind='barh',color='m',ax=ax9) #plt.tight_layout() #避免出现叠影 #plt.show()
2、较为简略方法绘图
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline fig, axes = plt.subplots(2,3,figsize=(20,10)) #这个可以方便同时建立画板画布 axes[0,1].plot(np.random.randn(10)) #第1行第二个画布绘图 axes[0,2].plot(np.random.randn(10),'g--',marker='o') arr = np.random.randn(20).cumsum() axes[1,1].plot(data,linestyle='--',color='red',marker='o') plt.plot(data,'k--') #未给定画布则在最后一个画布上绘图 axes[1,0].plot(arr,linestyle='dashed',color='yellow',marker='*') data = DataFrame(np.random.randn(2,3),columns=['a','b','c']) data.plot(ax=axes[0,0]) #针对DataFrame可以使用参数给定画布 #plt.show() #plt.savefig('test.png',dpi=400,bbox_inches='tight',facecolor='m') #保存到指定路径,dpi-像素,bbox_inches-剪除当前图表周围空白,facecolor-背景颜色
3-1、对一个DataFrame的几个列在不同画板同时作图
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline data11 = DataFrame(np.random.randn(100,4),columns=list('abcd')) data11.plot(subplots=True,figsize=(8,5),grid=False,title='my plot',legend=False,layout=(2,2))
3-2、对一个DataFrame的几个列在不同画板同时作图
import numpy as np from pandas import DataFrame import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False test = DataFrame(np.random.randn(10,10)) plt.subplot2grid((3,3),(0,0)) test.ix[:,0].plot(kind='bar') plt.ylabel(u'测试 y') plt.xlabel('test x') plt.subplot2grid((3,3), (0,1), colspan=2, rowspan=2) test.ix[:,1].plot(kind='kde',color='red') plt.grid(b=True, axis='y') plt.subplot2grid((3,3),(1,0)) test.ix[:,2].plot(kind='barh') plt.subplot2grid((3,3),(2,0)) plt.scatter(test.ix[:,3],test.ix[:,4]) plt.subplot2grid((3,3),(2,1)) test.ix[:,5].plot(ls='--') plt.subplot2grid((3,3),(2,2)) test.ix[:,6].plot(lw=2,color='green', alpha=.4,grid=True) plt.tight_layout();
4、画蜡烛图:
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.finance as mpf from pandas import Series, DataFrame from matplotlib.pylab import date2num %matplotlib inline plt.rcParams['figure.autolayout'] = True plt.rcParams['figure.figsize'] = 25,6 plt.rcParams['grid.alpha'] = .4 plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = ['SimHei'] fig, ax = plt.subplots(1,1,figsize=(12,5)) mpf.candlestick_ohlc(ax=ax,quotes=data2.values[::3],width=.002,colorup='red',colordown='green') plt.xticks(data2.date[::25],data.date.map(lambda x:x[:5])[::25],rotation=0) ax.twiny().plot(data3.Open) plt.tight_layout();
5、matplotlib画热图显示:
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline df = DataFrame(np.random.randn(10,10)) fig = plt.figure(figsize=(12,5)) ax = fig.add_subplot(111) axim = ax.imshow(df.values,interpolation='nearest')#cmap=plt.cm.gray_r, #cmap用来显示颜色,可以另行设置 plt.colorbar(axim) plt.show()
二、对图中的一些参数进行修改
1、对图表添加描述,修改x轴y轴区间
import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas import Series, DataFrame %matplotlib inline fig = plt.figure(figsize=(12,5)) ax = fig.add_subplot(111) ax.plot(np.random.randn(1000).cumsum(),linewidth=2,color='red') plt.axhline(y=0,linewidth=1,color='green',linestyle='-')#设置对比线 plt.axvline(x=500,linewidth=4,color='green',linestyle='--') #ticks = ax.set_xticks([0,250,500,750,1000]) #labels = ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small') ##这两个的效果可综合用下面的一个来描述 plt.xticks([0,250,500,750,1000],['one','two','three','four','five'],rotation=30,fontsize='small') #ax.set_title('Just for test') plt.title('Just for test')#作用同上 #ax.set_xlabel('ax x') plt.xlabel('ax x')#作用同上 #ax.set_ylabel('ax y') plt.ylabel('ax y')#作用同上 plt.grid() #plt.xlim([0,900]) #将x轴调整为0-900 #plt.ylim([-60,0]) #将y轴调整为-60-0 #plt.subplots_adjust(left=None,top=None,right=None,bottom=None,wspace=None,hspace=None)#用来修改间距。
2、给不同段的线设置不同的颜色
ser = Series(np.random.randn(24)) ser[:8].plot(color='red') ser[7:16].plot(color='green') ser[15:24].plot(color='blue')
3、给DataFrame作图时同时给用来作图的不同列设置颜色
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = 12,5 #设置图像大小 data = DataFrame(np.random.randn(100,2),columns=['one','two']) plt.plot(data['one'],'g-',data['two'],'r^') #颜色分别为green,red,linestyle分别为"-"和"^" plt.show()
4、图表添加描述或注释
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline fig, ax = plt.subplots(1,1) data = DataFrame(np.random.randn(10,3),columns=['one','two','three']) data.plot(ax=ax) plt.legend(loc='upper left') x = (data[['one']].idxmax()).values[0] y = data[['one']].max() ax.annotate('column one Highest point',xy=(x,y),xycoords='data',xytext=(+10,-25),textcoords='offset points', fontsize=14,arrowprops=dict(arrowstyle='->',color='k',linewidth=2)) plt.plot([1,1],[0,1],linestyle='--') plt.scatter(x=1,y=1,color='m') plt.text(1,0.5,'hello world',fontsize=14) plt.show()
5、对数据作拟合曲线:
import scipy as sp #需要引入scipy,这个需要额外安装,是一个类似于numpy的科学计算类库 from pandas import Series from matplotlib import pyplot as plt ser = Series(np.random.randn(100).cumsum()) x = ser.index #作为拟合的x y = ser.values #作为拟合的y fp1,residuals,rank,sv,rcond = sp.polyfit(x,y,1,full=True) #拟合为一阶多项式 fp5 = sp.polyfit(x,y,5) #拟合为五阶多项式 fp100 = sp.polyfit(x,y,120) #拟合为一百二十阶多项式 f1 = sp.poly1d(fp1) #转换为模型函数 f5 = sp.poly1d(fp5) f100 = sp.poly1d(fp100) fx1 = sp.linspace(0,x[-1],1000) #生成x值用来作图 fx5 = sp.linspace(0,x[-1],1000) fx100 = sp.linspace(0,x[-1],1000) ser.plot(color='yellow',linewidth=2) plt.plot(fx1,f1(fx1),linewidth=2,color='red') plt.plot(fx5,f5(fx5),linewidth=2,color='green') plt.plot(fx100,f100(fx100),linewidth=2,color='blue') plt.show()
6、一些样式设计
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline fig = plt.figure() fig.suptitle('bold figure suptitle', fontsize=14,fontweight='bold') ax = fig.add_subplot(111) fig.subplots_adjust(top=0.85) ax.set_title('axes title') ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') ax.text(3,8,'boxed italics text in data coords',style='italic', bbox={'facecolor':'red','alpha':0.5,'pad':10}) ax.text(2,6,r'an equation:$E=mc^2$',fontsize=15) ax.text(3,2,unicode('unicode: Institut f\374r Festk\366rperphysik', 'latin-1')) ax.text(0.95,0.01,'colored text in axes coords', verticalalignment='bottom',horizontalalignment='right', transform=ax.transAxes, color='green',fontsize=15) #其中verticalalignment、horizontalalignment可以分别用va、ha代替 ax.plot([2],[1],'o') ax.annotate('annotate',xy=(2,1),xytext=(3,4), arrowprops=dict(facecolor='black',shrink=.05)) ax.axis([0,10,0,10]) #ax.set_axis_off() #隐藏坐标系 plt.show()
7、将不同y轴的两个series画在同一个画板上
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt %matplotlib inline fig, ax = plt.subplots(1,1,figsize=(8,4)) data = DataFrame(np.random.randn(100,2),columns=['firstCol','secondCol']) data.firstCol = data.firstCol.map(lambda x:100*x) data.firstCol.cumsum().plot(ax=ax,color='blue') data.secondCol.cumsum().plot(ax=ax.twinx(),kind='line',color='red')
8、区域图
data = DataFrame(abs(np.random.randn(20,2)),columns=['one','two']) data.plot(kind='area',colormap='viridis_r',legend=False)
8.1、区间图
fig, ax = plt.subplots(1,1,figsize=(12,6)) ax.fill_between(range(20),np.random.randn(20),np.random.randn(20),alpha=.5) plt.grid(True);
mapcolor可设置为: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spectral, spectral_r, spring, spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, winter, winter_r
9、饼状图及参数设计
``` data = DataFrame(abs(np.random.randn(20,2)),columns=['one','two']) data.plot(subplots=True,kind='pie',legend=False, figsize=(6,3)); ``` import random plt.figure(figsize=(5,5)) plt.pie(data.ix[:, 0], autopct='%.2f%%', explode=[0.1, *[0]*19], pctdistance=0.8, labels=[''.join(random.sample(['a', 'b', 'c','d', 'e', 'f'], 2)) for _ in range(20)]);
fig, ax = plt.subplots(figsize=(10, 8), subplot_kw=dict(aspect="equal")) recipe = ["375 k U.S. Large Cap Blend", "300 k U.S. Large Cap Value", "75 k U.S. Short-Term Bonds", "50 k U.S. Small Cap Blend", "55 k U.S. Small Cap Value" , "95 k U.S. Real Estate", "250 k Intermediate-Term Bonds"] data = [float(x.split()[0]) for x in recipe] ingredients = [" ".join(x.split()[2:]) for x in recipe] def func(pct, allvals): absolute = int(pct/100. * np.sum(allvals)) return "{:.1f}%\n{:d} k".format(pct, absolute) explode = np.full(len(data), 0.1) wedges, texts, autotexts = ax.pie(data, explode=explode, autopct=lambda pct: func(pct, data), textprops=dict(color="w") ) ax.legend(wedges, ingredients, loc="center left", bbox_to_anchor=(1, 0, 0.5, 1)) plt.setp(autotexts, size=8, weight="bold");
10、设置轴的线条颜色,隐藏轴边框
import matplotlib.pyplot as plt import numpy as np import pandas as pd from pandas import Series,DataFrame %matplotlib inline ser = Series(np.random.randn(30)) fig, ax = plt.subplots(1,1) ser.plot() ax.spines['left'].set_color('green') ax.spines['bottom'].set_color('red') ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') plt.show()
11、翻转x轴,y轴(这个可以跟上面的对比,注意ticks显示)
import matplotlib.pyplot as plt import numpy as np import pandas as pd from pandas import Series,DataFrame %matplotlib inline ser = Series(np.random.randn(30)) fig, ax = plt.subplots(1,1) ser.plot() ax.spines['left'].set_color('green') ax.spines['bottom'].set_color('red') ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') plt.gca().invert_yaxis()#翻转y轴, plt.gca().invert_xaxis();#翻转x轴
12、隐藏x轴y轴
import numpy as np import pandas as pd import scipy as sp from matplotlib import pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False p1 = sp.polyfit([0,80,90],[-6390,0,-90],3) f1 = sp.poly1d(p1) p2 = sp.polyfit([100,30,110],[-6500,f1(30),-6400],3) f2 = sp.poly1d(p2) x = range(100) plt.rcParams['font.size'] = 18 fig, ax = plt.subplots(1,1,figsize=(12,8)) ax.plot(x,f1(x),lw=2) ax.plot(x,f2(x),lw=2) ax.plot(x,f1(x)+f2(x)+7000,lw=2) ax.set_xticks([]); ax.set_yticks([]); ax.annotate(u'总效应',xy=(30,f1(30)+f2(30)+7000),xytext=(35,-1000),arrowprops=dict(arrowstyle='->', linewidth=2.5)) ax.annotate(u'规模效应',xy=(45,f1(45)),xytext=(45,-3000),arrowprops=dict(arrowstyle='->', linewidth=2.5)) ax.annotate(u'激励效应',xy=(55,f2(55)),xytext=(45,-6000),arrowprops=dict(arrowstyle='->', linewidth=2.5)) plt.ylabel(u'环境效率') plt.xlabel(u'经营规模'); plt.xlim([0,95]);
12_1、突出指定坐标值
import numpy as np import matplotlib.pyplot as plt plt.plot(np.random.randn(100)) plt.xticks(list(range(100))[::20], list('ABCDE')) plt.gca().get_xticklabels()[2].set(weight='heavy', color='red');
12_2、设定x轴坐标显示方式
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np ax = plt.gca() # 获取当前轴 ax.locator_params(tight=True, nbins=5) # x显示为5个label值 ax.plot(np.random.normal(10, .1, 100));
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np ax = plt.gca() ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(7)) #设置x轴label显示为7的倍数 ax.plot(np.random.normal(10, .1, 100));
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np ax = plt.gca() ax.xaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%2.1f')) ax.plot(np.random.normal(10, .1, 100));
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import datetime fig = plt.figure(figsize=(12, 5)) ax = plt.gca() start = datetime.datetime(2012, 1, 1) stop = datetime.datetime(2012, 12, 31) delta = datetime.timedelta(days=1) dates = mpl.dates.drange(start, stop, delta) values = np.random.rand(len(dates)) ax.plot_date(dates, values, ls='-', marker='o', c='blue', alpha=.4) #date_format = mpl.dates.DateFormatter("%Y-%m-%d") #ax.xaxis.set_major_formatter(date_format) #fig.autofmt_xdate()
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np x1 = np.random.normal(30, 3, 100) x2 = np.random.normal(20, 2, 100) x3 = np.random.normal(10, 3, 100) plt.plot(x1, label='plot') plt.plot(x2, label='2nd plot') plt.plot(x3, label='last plot') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=3, mode='expand', borderaxespad=0.) plt.annotate("Import value", (55, 20), xycoords='data', xytext=(5, 38), arrowprops=dict(arrowstyle='->'));
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=(12, 6)) x = np.arange(0, 2, 0.01) y1 = np.sin(2*np.pi*x) y2 = 1.2 * np.sin(4 * np.pi * x) # fig = plt.figure() ax = plt.gca() ax.plot(x, y1, x, y2, color='k') ax.fill_between(x, y1, y2, where=y2>=y1, facecolor='darkblue', interpolate=False) ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='deeppink', interpolate=True);
from matplotlib import patheffects data = np.random.randn(70) fontsize = 18 plt.plot(data) title = 'This is figure title' x_label = "This is x axis label" y_label = "This is y axis label" title_text_obj = plt.title(title, fontsize=fontsize, va='bottom') title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()]) offset_xy = (1, -1) rgbRed = (1., 0., 0.) alpha = .8 pe = patheffects.withSimplePatchShadow(offset=offset_xy, shadow_rgbFace=rgbRed, alpha=alpha) xlabel_obj = plt.xlabel(x_label, fontsize=fontsize, alpha=.5) xlabel_obj.set_path_effects([pe]) ylabel_obj = plt.ylabel(y_label, fontsize=fontsize, alpha=.5) ylabel_obj.set_path_effects([pe]);
13、散点气泡图
from matplotlib import pyplot as plt %matplotlib inline for x,y in enumerate(range(10)): plt.scatter(x,y,s=100 * x+10, alpha=.3,edgecolors='red',linewidths=3) plt.grid(True);
14、箱体图
import random colors = ['red', 'green', 'lightgreen', 'cyan', 'purple', 'orange', 'blue'] p = plt.boxplot([range(10 * x + 10) for x in range(7)], notch=True, widths=0.5, positions=range(7),) plt.grid() for box in p['boxes']: box.set_color(random.choice(colors))
15、雷达图
import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.style.use('ggplot') values = [3.2, 2.1, 3.5, 2.8, 3] features = ['个人能力', 'QC知识', '解决问题能力', '服务质量意识', '团队精神'] N = len(values) angles = np.linspace(0, 2*np.pi, N, endpoint=False) values.append(values[0]) angles = np.append(angles, angles[0]) fig = plt.figure() ax = fig.add_subplot(111, polar=True) ax.plot(angles, values, 'o-', lw=2) ax.fill(angles, values, alpha=0.15) ax.set_thetagrids(angles*180/np.pi, features) ax.set_ylim(0, 5) plt.title('活动前后员工状态表现') plt.grid(True); #ax.grid(True);
16、3D图
曲面图
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline fig = plt.figure() ax = Axes3D(fig) X = np.arange(-2,2,0.1) Y = np.arange(-2,2,0.1) X, Y = np.meshgrid(X, Y) def f(x,y): return (1 - y** 5 + x ** 5) * np.exp(-x ** 2 - y ** 2) ax.plot_surface(X, Y, f(X, Y), rstride=1, cstride=1, color='red', alpha=.4);
改变颜色及仰角
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) X = np.arange(-2, 2, 0.1) Y = np.arange(-2, 2, 0.1) X, Y = np.meshgrid(X, Y) def f(x, y): return (1-y**5+pow(x, 5)) * np.exp(-pow(x, 2) - pow(y, 2)) ax.plot_surface(X, Y, f(X, Y), rstride=1, cmap=plt.cm.hot) ax.view_init(elev=10, azim=125)
散点图
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np xs = np.random.randint(30,40,100) ys = np.random.randint(20,30,100) zs = np.random.randint(10,20,100) xs2 = np.random.randint(50,60,100) ys2 = np.random.randint(30,40,100) zs2 = np.random.randint(50,70,100) xs3 = np.random.randint(10,30,100) ys3 = np.random.randint(40,50,100) zs3 = np.random.randint(40,50,100) fig = plt.figure() ax = Axes3D(fig) ax.scatter(xs, ys, zs) ax.scatter(xs2, ys2, zs2, c='r', marker='^') ax.scatter(xs3, ys3, zs3, c='g', marker='*') ax.set_xlabel('X label') ax.set_ylabel('Y label') ax.set_ylabel('Z label');
直方图
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D x = np.arange(8) y = np.random.randint(0,10,8) y2 = y + np.random.randint(0,3,8) y3 = y2 + np.random.randint(0,3,8) y4 = y3 + np.random.randint(0,3,8) y5 = y4 + np.random.randint(0,3,8) clr = ['red', 'green', 'blue', 'black'] * 2 fig = plt.figure() ax = Axes3D(fig) ax.bar(x, y, 0,zdir='y', color=clr) ax.bar(x, y2, 10,zdir='y', color=clr) ax.bar(x, y3, 20,zdir='y', color=clr) ax.bar(x, y4, 30,zdir='y', color=clr) ax.bar(x, y5, 40,zdir='y', color=clr) ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') ax.view_init(elev=40);
嵌套图
import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([.1, .1, .8, .8]) inner_ax = fig.add_axes([.2, .6, .25, .25]) ax.plot(np.arange(10)) inner_ax.plot(np.arange(10));
others
其他。。。
1、一些参数缩写形式:
_alias_map = {'color': ['c'], 'linewidth': ['lw'], 'linestyle': ['ls'], 'facecolor': ['fc'], 'edgecolor': ['ec'], 'markerfacecolor': ['mfc'], 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markersize': ['ms'], }
2、一些参数含义介绍:
bins 柱形个数
color 颜色,其中c,m,y,k分别代表青,滇红,黄,黑,别的如g–green,b–blue,可以选用RGB值如’#CECECE’等等
plt.grid(True) #plt.grid() 显示网格
plt.autoscale(tight=True)#plt.autoscale()自动最佳化比例
plt.legend(loc=‘best’)#loc=right
center left
upper right
lower right
best
center
lower left
center right
upper left
upper center
lower center
等等,图例安放位置,一般选用‘best’即可,自动帮你选择最佳位置=============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== =============
label=‘。。。’#图例名
style=‘g–’#颜色为绿色,线条风格为‘–’========== ======== character color ========== ======== 'b' blue 'g' green 'r' red 'c' cyan 'm' magenta 'y' yellow 'k' black 'w' white ========== ========
linestyle=’–’,#线条风格
================ =============================== character description ================ =============================== ``'-'`` solid line style ``'--'`` dashed line style ``'-.'`` dash-dot line style ``':'`` dotted line style ``'.'`` 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 ================ ===============================
drawstyle=‘steps_post’#线条类型
marker=‘o’#标识类型
rotation=30#顺时针旋转30,一般用于x轴显示
fontsize=‘small’#文字显示大小
kind=‘bar’#图表显示类型,有’barh’,‘scatter’,'kde’等等
stacked=True#是否堆积,用于kind='bar’或’barh’时
alpha=0.2#显示透明度
plt.subplots(2,2,sharex=True,sharey=True)#同一x轴y轴
plt.adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)#修改间距
plt.xlim([0,20])#修改当前x轴绘制范围
plt.ylim([0,20])#修改当前y轴绘制范围
facecolor#图像的背景色
edgecolor#图像的背景色
legend=False#当以dataframe作图时会自动默认列名为图标,如不想显示则设置为False#plt.title('alpha>beta') #plt.title(r'$\alpha >\beta$') #plt.title(r'$\alpha_i>\beta_i$') plt.title(r'$\sum_{i=0}^\infty x_i$')
3、matplotlib默认设置:
可以通过plt.rcParams动态修改使用。### MATPLOTLIBRC FORMAT # This is a sample matplotlib configuration file - you can find a copy # of it on your system in # site-packages/matplotlib/mpl-data/matplotlibrc. If you edit it # there, please note that it will be overridden in your next install. # If you want to keep a permanent local copy that will not be # over-written, place it in HOME/.matplotlib/matplotlibrc (unix/linux # like systems) and C:\Documents and Settings\yourname\.matplotlib # (win32 systems). # # This file is best viewed in a editor which supports python mode # syntax highlighting. Blank lines, or lines starting with a comment # symbol, are ignored, as are trailing comments. Other lines must # have the format # key : val # optional comment # # Colors: for the color values below, you can either use - a # matplotlib color string, such as r, k, or b - an rgb tuple, such as # (1.0, 0.5, 0.0) - a hex string, such as ff00ff or #ff00ff - a scalar # grayscale intensity such as 0.75 - a legal html color name, eg red, # blue, darkslategray #### CONFIGURATION BEGINS HERE # the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg # MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template # You can also deploy your own backend outside of matplotlib by # referring to the module name (which must be in the PYTHONPATH) as # ’module://my_backend’ backend : GTKAgg # If you are using the Qt4Agg backend, you can choose here # to use the PyQt4 bindings or the newer PySide bindings to # the underlying Qt4 toolkit. #backend.qt4 : PyQt4 # PyQt4 | PySide # Note that this can be overridden by the environment variable 24 Chapter 5. # QT_API used by Enthought Tool Suite (ETS); valid values are # "pyqt" and "pyside". The "pyqt" setting has the side effect of # forcing the use of Version 2 API for QString and QVariant. # if you are runing pyplot inside a GUI and your backend choice # conflicts, we will automatically try to find a compatible one for # you if backend_fallback is True #backend_fallback: True #interactive : False #toolbar : toolbar2 # None | classic | toolbar2 #timezone : UTC # a pytz timezone string, eg US/Central or Europe/Paris # Where your matplotlib data lives if you installed to a non-default # location. This is where the matplotlib fonts, bitmaps, etc reside #datapath : /home/jdhunter/mpldata ### LINES # See http://matplotlib.sourceforge.net/api/artist_api.html#module-matplotlib.lines for more # information on line properties. #lines.linewidth : 1.0 # line width in points #lines.linestyle : - # solid line #lines.color : blue #lines.marker : None # the default marker #lines.markeredgewidth : 0.5 # the line width around the marker symbol #lines.markersize : 6 # markersize, in points #lines.dash_joinstyle : miter # miter|round|bevel #lines.dash_capstyle : butt # butt|round|projecting #lines.solid_joinstyle : miter # miter|round|bevel #lines.solid_capstyle : projecting # butt|round|projecting #lines.antialiased : True # render lines in antialised (no jaggies) ### PATCHES # Patches are graphical objects that fill 2D space, like polygons or # circles. See # http://matplotlib.sourceforge.net/api/artist_api.html#module-matplotlib.patches # information on patch properties #patch.linewidth : 1.0 # edge width in points #patch.facecolor : blue #patch.edgecolor : black #patch.antialiased : True # render patches in antialised (no jaggies) ### FONT # # font properties used by text.Text. See # http://matplotlib.sourceforge.net/api/font_manager_api.html for more # information on font properties. The 6 font properties used for font # matching are given below with their default values. # # The font.family property has five values: ’serif’ (e.g. Times), # ’sans-serif’ (e.g. Helvetica), ’cursive’ (e.g. Zapf-Chancery), # ’fantasy’ (e.g. Western), and ’monospace’ (e.g. Courier). Each of 5.2. Dynamic rc settings 25Matplotlib, Release 1.1.0 # these font families has a default list of font names in decreasing # order of priority associated with them. # # The font.style property has three values: normal (or roman), italic # or oblique. The oblique style will be used for italic, if it is not # present. # # The font.variant property has two values: normal or small-caps. For # TrueType fonts, which are scalable fonts, small-caps is equivalent # to using a font size of ’smaller’, or about 83% of the current font # size. # # The font.weight property has effectively 13 values: normal, bold, # bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as # 400, and bold is 700. bolder and lighter are relative values with # respect to the current weight. # # The font.stretch property has 11 values: ultra-condensed, # extra-condensed, condensed, semi-condensed, normal, semi-expanded, # expanded, extra-expanded, ultra-expanded, wider, and narrower. This # property is not currently implemented. # # The font.size property is the default font size for text, given in pts. # 12pt is the standard value. # #font.family : sans-serif #font.style : normal #font.variant : normal #font.weight : medium #font.stretch : normal # note that font.size controls default text sizes. To configure # special text sizes tick labels, axes, labels, title, etc, see the rc # settings for axes and ticks. Special text sizes can be defined # relative to font.size, using the following values: xx-small, x-small, # small, medium, large, x-large, xx-large, larger, or smaller #font.size : 12.0 #font.serif : Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, #font.sans-serif : Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, He #font.cursive : Apple Chancery, Textile, Zapf Chancery, Sand, cursive #font.fantasy : Comic Sans MS, Chicago, Charcoal, Impact, Western, fantasy #font.monospace : Bitstream Vera Sans Mono, Andale Mono, Nimbus Mono L, Courier New, ### TEXT # text properties used by text.Text. See # http://matplotlib.sourceforge.net/api/artist_api.html#module-matplotlib.text for more # information on text properties #text.color : black ### LaTeX customizations. See http://www.scipy.org/Wiki/Cookbook/Matplotlib/UsingTex #text.usetex : False # use latex for all text handling. The following fonts # are supported through the usual rc parameter settings: # new century schoolbook, bookman, times, palatino, 26 Chapter 5. # zapf chancery, charter, serif, sans-serif, helvetica, # avant garde, courier, monospace, computer modern roman, # computer modern sans serif, computer modern typewriter # If another font is desired which can loaded using the # LaTeX \usepackage command, please inquire at the # matplotlib mailing list #text.latex.unicode : False # use "ucs" and "inputenc" LaTeX packages for handling # unicode strings. #text.latex.preamble : # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES # AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP # IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO. # preamble is a comma separated list of LaTeX statements # that are included in the LaTeX document preamble. # An example: # text.latex.preamble : \usepackage{bm},\usepackage{euler} # The following packages are always loaded with usetex, so # beware of package collisions: color, geometry, graphicx, # type1cm, textcomp. Adobe Postscript (PSSNFS) font packages # may also be loaded, depending on your font settings #text.dvipnghack : None # some versions of dvipng don’t handle alpha # channel properly. Use True to correct # and flush ~/.matplotlib/tex.cache # before testing and False to force # correction off. None will try and # guess based on your dvipng version #text.hinting : True # If True, text will be hinted, otherwise not. This only # affects the Agg backend. # The following settings allow you to select the fonts in math mode. # They map from a TeX font name to a fontconfig font pattern. # These settings are only used if mathtext.fontset is ’custom’. # Note that this "custom" mode is unsupported and may go away in the # future. #mathtext.cal : cursive #mathtext.rm : serif #mathtext.tt : monospace #mathtext.it : serif:italic #mathtext.bf : serif:bold #mathtext.sf : sans #mathtext.fontset : cm # Should be ’cm’ (Computer Modern), ’stix’, # ’stixsans’ or ’custom’ #mathtext.fallback_to_cm : True # When True, use symbols from the Computer Modern # fonts when a symbol can not be found in one of # the custom math fonts. #mathtext.default : it # The default font to use for math. # Can be any of the LaTeX font names, including # the special name "regular" for the same font # used in regular text. ### AXES # default face and edge color, default tick sizes, # default fontsizes for ticklabels, and so on. See # http://matplotlib.sourceforge.net/api/axes_api.html#module-matplotlib.axes #axes.hold : True # whether to clear the axes by default on #axes.facecolor : white # axes background color #axes.edgecolor : black # axes edge color #axes.linewidth : 1.0 # edge linewidth #axes.grid : False # display grid or not #axes.titlesize : large # fontsize of the axes title #axes.labelsize : medium # fontsize of the x any y labels #axes.labelweight : normal # weight of the x and y labels #axes.labelcolor : black #axes.axisbelow : False # whether axis gridlines and ticks are below # the axes elements (lines, text, etc) #axes.formatter.limits : -7, 7 # use scientific notation if log10 # of the axis range is smaller than the # first or larger than the second #axes.formatter.use_locale : False # When True, format tick labels # according to the user’s locale. # For example, use ’,’ as a decimal # separator in the fr_FR locale. #axes.unicode_minus : True # use unicode for the minus symbol # rather than hypen. See # http://en.wikipedia.org/wiki/Plus_sign #axes.color_cycle : b, g, r, c, m, y, k # color cycle for plot lines # as list of string colorspecs: # single letter, long name, or # web-style hex #polaraxes.grid : True # display grid on polar axes #axes3d.grid : True # display grid on 3d axes ### TICKS # see http://matplotlib.sourceforge.net/api/axis_api.html#matplotlib.axis.Tick #xtick.major.size : 4 # major tick size in points #xtick.minor.size : 2 # minor tick size in points #xtick.major.pad : 4 # distance to major tick label in points #xtick.minor.pad : 4 # distance to the minor tick label in points #xtick.color : k # color of the tick labels #xtick.labelsize : medium # fontsize of the tick labels #xtick.direction : in # direction: in or out #ytick.major.size : 4 # major tick size in points #ytick.minor.size : 2 # minor tick size in points #ytick.major.pad : 4 # distance to major tick label in points #ytick.minor.pad : 4 # distance to the minor tick label in points #ytick.color : k # color of the tick labels #ytick.labelsize : medium # fontsize of the tick labels #ytick.direction : in # direction: in or out ### GRIDS #grid.color : black # grid color #grid.linestyle : : # dotted #grid.linewidth : 0.5 # in points ### Legend #legend.fancybox : False # if True, use a rounded box for the # legend, else a rectangle #legend.isaxes : True #legend.numpoints : 2 # the number of points in the legend line #legend.fontsize : large #legend.pad : 0.0 # deprecated; the fractional whitespace inside the legend border #legend.borderpad : 0.5 # border whitspace in fontsize units #legend.markerscale : 1.0 # the relative size of legend markers vs. original # the following dimensions are in axes coords #legend.labelsep : 0.010 # deprecated; the vertical space between the legend entries #legend.labelspacing : 0.5 # the vertical space between the legend entries in fraction of fontsize #legend.handlelen : 0.05 # deprecated; the length of the legend lines #legend.handlelength : 2. # the length of the legend lines in fraction of fontsize #legend.handleheight : 0.7 # the height of the legend handle in fraction of fontsize #legend.handletextsep : 0.02 # deprecated; the space between the legend line and legend text #legend.handletextpad : 0.8 # the space between the legend line and legend text in fr #legend.axespad : 0.02 # deprecated; the border between the axes and legend edge #legend.borderaxespad : 0.5 # the border between the axes and legend edge in fraction of fontsize #legend.columnspacing : 2. # the border between the axes and legend edge in fraction of fontsize #legend.shadow : False #legend.frameon : True # whether or not to draw a frame around legend ### FIGURE # See http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure #figure.figsize : 8, 6 # figure size in inches #figure.dpi : 80 # figure dots per inch #figure.facecolor : 0.75 # figure facecolor; 0.75 is scalar gray #figure.edgecolor : white # figure edgecolor # The figure subplot parameters. All dimensions are fraction of the # figure width or height #figure.subplot.left : 0.125 # the left side of the subplots of the figure #figure.subplot.right : 0.9 # the right side of the subplots of the figure #figure.subplot.bottom : 0.1 # the bottom of the subplots of the figure #figure.subplot.top : 0.9 # the top of the subplots of the figure #figure.subplot.wspace : 0.2 # the amount of width reserved for blank space between subplots #figure.subplot.hspace : 0.2 # the amount of height reserved for white space between subplots ### IMAGES #image.aspect : equal # equal | auto | a number #image.interpolation : bilinear # see help(imshow) for options #image.cmap : jet # gray | jet etc... #image.lut : 256 # the size of the colormap lookup table #image.origin : upper # lower | upper #image.resample : False ### CONTOUR PLOTS #contour.negative_linestyle : dashed # dashed | solid ### Agg rendering ### Warning: experimental, 2008/10/10 #agg.path.chunksize : 0 # 0 to disable; values in the range # 10000 to 100000 can improve speed slightly # and prevent an Agg rendering failure # when plotting very large data sets, # especially if they are very gappy. # It may cause minor artifacts, though. # A value of 20000 is probably a good # starting point. ### SAVING FIGURES #path.simplify : True # When True, simplify paths by removing "invisible" # points to reduce file size and increase rendering # speed #path.simplify_threshold : 0.1 # The threshold of similarity below which # vertices will be removed in the simplification # process #path.snap : True # When True, rectilinear axis-aligned paths will be snapped to # the nearest pixel when certain criteria are met. When False, # paths will never be snapped. # the default savefig params can be different from the display params # Eg, you may want a higher resolution, or to make the figure # background white #savefig.dpi : 100 # figure dots per inch #savefig.facecolor : white # figure facecolor when saving #savefig.edgecolor : white # figure edgecolor when saving #savefig.extension : auto # what extension to use for savefig(’foo’), or ’auto’ #cairo.format : png # png, ps, pdf, svg # tk backend params #tk.window_focus : False # Maintain shell focus for TkAgg # ps backend params #ps.papersize : letter # auto, letter, legal, ledger, A0-A10, B0-B10 #ps.useafm : False # use of afm fonts, results in small files #ps.usedistiller : False # can be: None, ghostscript or xpdf # Experimental: may produce smaller files. # xpdf intended for production of publication quality files, # but requires ghostscript, xpdf and ps2eps #ps.distiller.res : 6000 # dpi #ps.fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType) # pdf backend params #pdf.compression : 6 # integer from 0 to 9 # 0 disables compression (good for debugging) #pdf.fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType) # svg backend params #svg.image_inline : True # write raster image data directly into the svg file #svg.image_noscale : False # suppress scaling of raster data embedded in SVG #svg.fonttype : ’path’ # How to handle SVG fonts: # ’none’: Assume fonts are installed on the machine where the SVG will be viewed. # ’path’: Embed characters as paths -- supported by most SVG renderers # ’svgfont’: Embed characters as SVG fonts -- supported only by Chrome, # Opera and Safari # docstring params #docstring.hardcopy = False # set this when you want to generate hardcopy docstring # Set the verbose flags. This controls how much information # matplotlib gives you at runtime and where it goes. The verbosity # levels are: silent, helpful, debug, debug-annoying. Any level is # inclusive of all the levels below it. If your setting is "debug", # you’ll get all the debug and helpful messages. When submitting # problems to the mailing-list, please set verbose to "helpful" or "debug" # and paste the output into your report. # # The "fileo" gives the destination for any calls to verbose.report. # These objects can a filename, or a filehandle like sys.stdout. # # You can override the rc default verbosity from the command line by # giving the flags --verbose-LEVEL where LEVEL is one of the legal # levels, eg --verbose-helpful. # # You can access the verbose instance in your code # from matplotlib import verbose. #verbose.level : silent # one of silent, helpful, debug, debug-annoying #verbose.fileo : sys.stdout # a log filename, sys.stdout or sys.stderr # Event keys to interact with figures/plots via keyboard. # Customize these settings according to your needs. # Leave the field(s) empty if you don’t need a key-map. (i.e., fullscreen : ’’) #keymap.fullscreen : f # toggling #keymap.home : h, r, home # home or reset mnemonic #keymap.back : left, c, backspace # forward / backward keys to enable #keymap.forward : right, v # left handed quick navigation #keymap.pan : p # pan mnemonic #keymap.zoom : o # zoom mnemonic #keymap.save : s # saving current figure #keymap.grid : g # switching on/off a grid in current axes #keymap.yscale : l # toggle scaling of y-axes (’log’/’linear’) #keymap.xscale : L, k # toggle scaling of x-axes (’log’/’linear’) #keymap.all_axes : a # enable all axes # Control downloading of example data. Various examples download some # data from the Matplotlib git repository to avoid distributing extra # files, but sometimes you want to avoid that. In that case set # examples.download to False and examples.directory to the directory # where you have a checkout of https://github.com/matplotlib/sample_data #examples.download : True # False to bypass downloading mechanism #examples.directory : ’’ # directory to look in if download is false
这个
repo
用来记录一些python技巧、书籍、学习链接等,欢迎star
github地址
-
Python三维绘图--Matplotlib
2019-05-08 13:08:14python的matplotlib库就包含了丰富的三维绘图工具。 1.创建三维坐标轴对象Axes3D 创建Axes3D主要有两种方式,一种是利用关键字projection='3d'l来实现,另一种则是通过从mpl_toolkits.mplot3d导入对象Axes3D来...Python三维绘图
在遇到三维数据时,三维图像能给我们对数据带来更加深入地理解。python的matplotlib库就包含了丰富的三维绘图工具。
1.创建三维坐标轴对象
Axes3D
创建
Axes3D
主要有两种方式,一种是利用关键字projection='3d'
l来实现,另一种则是通过从mpl_toolkits.mplot3d
导入对象Axes3D
来实现,目的都是生成具有三维格式的对象Axes3D
.#方法一,利用关键字 from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D #定义坐标轴 fig = plt.figure() ax1 = plt.axes(projection='3d') #ax = fig.add_subplot(111,projection='3d') #这种方法也可以画多个子图 #方法二,利用三维轴方法 from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D #定义图像和三维格式坐标轴 fig=plt.figure() ax2 = Axes3D(fig)
2.三维曲线和散点
随后在定义的坐标轴上画图:
import numpy as np z = np.linspace(0,13,1000) x = 5*np.sin(z) y = 5*np.cos(z) zd = 13*np.random.random(100) xd = 5*np.sin(zd) yd = 5*np.cos(zd) ax1.scatter3D(xd,yd,zd, cmap='Blues') #绘制散点图 ax1.plot3D(x,y,z,'gray') #绘制空间曲线 plt.show()
3.三维曲面
下一步画三维曲面:
fig = plt.figure() #定义新的三维坐标轴 ax3 = plt.axes(projection='3d') #定义三维数据 xx = np.arange(-5,5,0.5) yy = np.arange(-5,5,0.5) X, Y = np.meshgrid(xx, yy) Z = np.sin(X)+np.cos(Y) #作图 ax3.plot_surface(X,Y,Z,cmap='rainbow') #ax3.contour(X,Y,Z, zdim='z',offset=-2,cmap='rainbow) #等高线图,要设置offset,为Z的最小值 plt.show()
如果加入渲染时的步长,会得到更加清晰细腻的图像:
ax3.plot_surface(X,Y,Z,rstride = 1, cstride = 1,cmap='rainbow')
,其中的row和cloum_stride为横竖方向的绘图采样步长,越小绘图越精细。
4.等高线
同时还可以将等高线投影到不同的面上:
from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D #定义坐标轴 fig4 = plt.figure() ax4 = plt.axes(projection='3d') #生成三维数据 xx = np.arange(-5,5,0.1) yy = np.arange(-5,5,0.1) X, Y = np.meshgrid(xx, yy) Z = np.sin(np.sqrt(X**2+Y**2)) #作图 ax4.plot_surface(X,Y,Z,alpha=0.3,cmap='winter') #生成表面, alpha 用于控制透明度 ax4.contour(X,Y,Z,zdir='z', offset=-3,cmap="rainbow") #生成z方向投影,投到x-y平面 ax4.contour(X,Y,Z,zdir='x', offset=-6,cmap="rainbow") #生成x方向投影,投到y-z平面 ax4.contour(X,Y,Z,zdir='y', offset=6,cmap="rainbow") #生成y方向投影,投到x-z平面 #ax4.contourf(X,Y,Z,zdir='y', offset=6,cmap="rainbow") #生成y方向投影填充,投到x-z平面,contourf()函数 #设定显示范围 ax4.set_xlabel('X') ax4.set_xlim(-6, 4) #拉开坐标轴范围显示投影 ax4.set_ylabel('Y') ax4.set_ylim(-4, 6) ax4.set_zlabel('Z') ax4.set_zlim(-3, 3) plt.show()
5.随机散点图
可以利用
scatter()
生成各种不同大小,颜色的散点图,其参数如下:#函数定义 matplotlib.pyplot.scatter(x, y, s=None, #散点的大小 array scalar c=None, #颜色序列 array、sequency marker=None, #点的样式 cmap=None, #colormap 颜色样式 norm=None, #归一化 归一化的颜色camp vmin=None, vmax=None, #对应上面的归一化范围 alpha=None, #透明度 linewidths=None, #线宽 verts=None, # edgecolors=None, #边缘颜色 data=None, **kwargs ) #ref:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html
from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D #定义坐标轴 fig4 = plt.figure() ax4 = plt.axes(projection='3d') #生成三维数据 xx = np.random.random(20)*10-5 #取100个随机数,范围在5~5之间 yy = np.random.random(20)*10-5 X, Y = np.meshgrid(xx, yy) Z = np.sin(np.sqrt(X**2+Y**2)) #作图 ax4.scatter(X,Y,Z,alpha=0.3,c=np.random.random(400),s=np.random.randint(10,20, size=(20, 40))) #生成散点.利用c控制颜色序列,s控制大小 #设定显示范围 plt.show()
Finish
Todo bar
-
【数据展示】matplotlib设置画面大小
2018-08-04 09:54:02代码实例 plt.figure(figsize=(6, 6.5)) 注意,这里的画面大小其实是 600 * 650的。...import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=(6, 6.5)) for i in range(4): ax = plt.s... -
python matplotlib 中文设置
2019-12-15 13:04:12font_list=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist]) for i in font_list: print (i) 会有很多,然后找一个字体设置一下就好了 只要这一句就好了,字体自己可以修改 ... -
Python绘图库Matplotlib.pyplot之网格线设置(plt.grid())
2018-07-16 10:28:31首先导入需要用到的库,matplotlib.pyplot是必须的,Numpy是为了生成画布用的。 import numpy as np import matplotlib.pyplot as plt 生成网格 plt.gcf().set_facecolor(np.ones(3)* 240 /... -
python matplotlib 画图保存图片简单例子
2018-03-21 15:10:04保存的时候遇到过保存空白图像的问题,是因为将plt.savefig('./test2.jpg')放到了plt.show()之后,...import matplotlib.pyplot as plt t = np.arange(0, 69, 1) plt.plot(t, t, 'r', t, t**2, 'b') label =... -
Matplotlib绘制动画
2017-10-19 16:49:33使用matplotlib制作静态图表的例子很多,matplotlib的优势在使用Python技术栈实现于类似Matlab风格的图表。 制作动态图表的选择很多,特别是js系,比如Highcharts或者百度的Echarts。 使用matplotlib绘制动画官网... -
Matplotlib 数据分析可视化
2019-08-30 15:43:53数据分析三剑客,NumPy、Pandas、Matplotlib,本课程是对Matplotlib的讲解,Matplotlib可以是分析的数据可视化,可以更直观的查看数据分析的结果,本课程独辟蹊径,不光教大家如何绘图,例如:饼图、柱状图、条形图... -
matplotlib的下载与安装教程
2018-07-10 15:41:50安装完python之后(确保配置正确,博主的版本号为3.6.5,目测以上的都行),对应...# Windowspip install matplotlib# MacOSpip3 install matplotlib# Linuxsudo apt-get install python3-tkpip3 install matplotlib... -
Matplotlib 安装
2019-10-24 11:35:19章节Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 Matplotlib 其他类型图形 Matplotlib 柱状图 Matplotlib 饼图 Matplotlib 直方图 Matplotlib 散点图 ... -
Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围
2019-05-07 11:23:17import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y_values=[x**2 for x in x_values] #y轴的数字是x轴数字的平方 plt.plot(x_values,y_values,c='green') #用plot函数绘制... -
Python第三方库matplotlib(2D绘图库)入门与进阶
2018-03-14 18:56:01Matplotlib 简介: Matplotlib是一个Python 2D绘图库,它可以在各种平台上以各种硬拷贝格式和交互式环境生成出具有出版品质的图形。 Matplotlib可用于Python脚本,Python和IPython shell,Jupyter笔记本,... -
Pycharm安装matplotlib
2018-08-14 23:26:13在终端中通过pip3安装matplotlib后,发现pycharm中引入会报错,查了一下发现可以在Pycharm中安装matplotlib来解决: 1. 打开Preferences,找到Project Interpreter,点“+”添加 2. 在输入框中输入matplotlib... -
Matplotlib 教程
2019-10-24 11:24:12Matplotlib是python中最流行的数据绘图库,使用matplotlib,您可以绘制任何类型的图形。 本教程的目标是让您轻松学会使用matplotlib绘制复杂的图形。 预备知识 熟悉Python语言编程 了解NumPy库 章节Matplotlib ... -
matplotlib xticks用法
2019-08-08 16:19:31这个坐标轴变名用法,我真服气了,我在网上看大家写的教程,看的头晕,也没看懂他们写xtick到底怎么用的,...import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [1, 4, 9, 6] labels = ['Frogs', 'Hogs', ... -
matplotlib多个饼状图
2020-03-11 16:47:13import matplotlib.pyplot as plt import matplotlib.font_manager as fm myfont = fm.FontProperties(fname=r'/home/chenyang/PycharmProjects/show_face_decetor/fonts/simsun.ttf') fig = plt.figure("tu") ax_li... -
在matplotlib中显示中文
2017-10-11 11:28:17matplotlib显示不了中文,主要问题在于没有指定中文字体。 解决方法有有很多种,有修改matplotlib配置文件,还有替换matplotlib的mpl-data文件夹下字体文件的,这些方法不够灵活,以下两种方法相对灵活一些。方法一... -
Matplotlib中%matplotlib inline
2018-10-14 23:47:35我们在使用GitHub上的代码时,经常可以看到%matplotlib inline这一行,无论用哪个python的IDE如spyder或者pycharm,这个地方都会报错,显示是invalid syntax。 import tensorflow as tf import numpy as np import ... -
Python绘图问题:Matplotlib中指定图片大小和像素
2018-06-13 14:23:59matplotlib.rcParams[‘figure.figsize’]#图片像素 matplotlib.rcParams[‘savefig.dpi’]#分辨率 plt.savefig(‘plot123_2.png’, dpi=200)#指定分辨率 plt.rcParams['figure.figsize'] = (8.0, 4.0) #... -
使用matplotlib绘制折线图,柱状图,柱线混合图
2019-08-31 21:54:49matplotlib介绍 Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。 它也可以和图形工具包一起使用,如 PyQt 和 wxPython。 安装Matplotlib库命令:在cmd命令窗口... -
matplotlib安装
2018-05-24 01:08:45我是之前已经安装了pip,所以现在直接用pip安装matplotlib模块。调出cmd窗口,然后 1. 执行 python -m pip install -U pip setuptools 进行升级2. 执行 python -m pip install matplotlib 进行自动下载安装3. 执行 ... -
Py之matplotlib.pyplot:matplotlib.pyplot的plt.legend函数的简介、使用方法之详细攻略
2021-01-04 23:41:54Py之matplotlib.pyplot:matplotlib.pyplot的plt.legend函数的简介、使用方法之详细攻略 目录 matplotlib.pyplot的plt.legend函数的简介 1、参数解释 2、源代码 matplotlib.pyplot的plt.legend函数的... -
vscode matplotlib
2018-07-13 15:01:16ModuleNotFoundError: No module named ‘tkinter’ solver #%% import matplotlib ubuntu sudo apt install python3-tk or # don't show so we should save the ...import matplotlib matplotlib.use... -
Py之matplotlib:matplotlib绘图自定义函数总结
2018-07-13 12:51:11Py之matplotlib:matplotlib绘图自定义函数总结 目录 实现结果 实现结果 1、两个函数 Keys,Values=list_count(list_address) draw(Keys,Values,title,xlabel,ylabel) 2、twoD_in_different_... -
Py之Matplotlib:python包之Matplotlib库图表绘制包的简介、安装、使用方法(matplotlib颜色大全)详细攻略
2018-01-22 23:41:48Py之Matplotlib:python包之Matplotlib库图表绘制包的简介、安装、使用方法详细攻略 目录 Matplotlib简介 matplotlib安装 matplotlib的使用方法 1、字体选择参数 2、绘制的颜色、线型等参数 matplotlib的... -
matplotlib作图
2017-04-17 18:25:15matplotlib 是Python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。它的文档相当完备,并且Gallery页面 中
-
写卡号软件1.9.rar
-
Unity游戏开发之数字华容道
-
橙色儿童艺术表演网页模板
-
school.sql
-
算法导论(基础知识)——编程大牛的必经之路
-
FFmpeg4.3黄金系列课程:c++版
-
Hive中join语法总结
-
天若OCR开源版V5.0.0.zip
-
gltf-pipeline-3.0.2.zip
-
之前一些好用的架包Android架包自动初始化id,以及GsonFormat等等
-
可爱童话美容会所网页模板
-
thinkphp5.1博客后台实战视频
-
java实现HTTP请求的三种方式
-
【数据分析-随到随学】Python数据获取
-
官方VJC1.564.rar
-
【数据分析-随到随学】Spark理论及实战
-
惠海半导体H7310恒流LED控制芯片,线性恒流驱动照明解决方案
-
第3章 入门程序、常量、变量
-
存货发完
-
【安全资讯】2021年值得关注的10大网络安全工具