您的当前位置:首页>关注 > 正文

python中的matplotlib:创建图表的绘图包:世界速看料

来源:CSDN 时间:2023-03-30 09:11:12

这个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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinefig = 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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinefig, 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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinedata11 = 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 npfrom pandas import DataFrameimport matplotlib.pyplot as plt%matplotlib inlineplt.rcParams["font.sans-serif"] = ["SimHei"]plt.rcParams["axes.unicode_minus"] = Falsetest = 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 npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.finance as mpffrom pandas import Series, DataFramefrom matplotlib.pylab import date2num%matplotlib inlineplt.rcParams["figure.autolayout"] = Trueplt.rcParams["figure.figsize"] = 25,6plt.rcParams["grid.alpha"] = .4plt.rcParams["axes.unicode_minus"] = Falseplt.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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinedf = 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 pdimport numpy as npimport matplotlib.pyplot as pltfrom pandas import Series, DataFrame%matplotlib inlinefig = 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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlineplt.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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinefig, 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 Seriesfrom matplotlib import pyplot as pltser = Series(np.random.randn(100).cumsum())x = ser.index  #作为拟合的xy = ser.values  #作为拟合的yfp1,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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinefig = 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 npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as plt%matplotlib inlinefig, 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)); ``` ![这里写图片描述](https://imgconvert.csdnimg.cn/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTcwODE1MTY0ODI4OTgx?x-oss-process=image/format,png)

import randomplt.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 pltimport numpy as npimport pandas as pdfrom pandas import Series,DataFrame%matplotlib inlineser = 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 pltimport numpy as npimport pandas as pdfrom pandas import Series,DataFrame%matplotlib inlineser = 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 npimport pandas as pdimport scipy as spfrom matplotlib import pyplot as plt%matplotlib inlineplt.rcParams["font.sans-serif"] = ["SimHei"]plt.rcParams["axes.unicode_minus"] = Falsep1 = 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"] = 18fig, 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 npimport matplotlib.pyplot as pltplt.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 mplimport matplotlib.pyplot as pltimport numpy as npax = plt.gca()  # 获取当前轴ax.locator_params(tight=True, nbins=5)  # x显示为5个label值ax.plot(np.random.normal(10, .1, 100));

import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npax = 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 mplimport matplotlib.pyplot as pltimport numpy as npax = plt.gca()ax.xaxis.set_major_formatter(mpl.ticker.FormatStrFormatter("%2.1f"))ax.plot(np.random.normal(10, .1, 100));

import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npimport datetimefig = 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 mplimport matplotlib.pyplot as pltimport numpy as npx1 = 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 mplimport matplotlib.pyplot as pltimport numpy as npplt.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 patheffectsdata = np.random.randn(70)fontsize = 18plt.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 = .8pe = 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 inlinefor 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 randomcolors = ["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、雷达图

![参考](https://imgconvert.csdnimg.cn/aHR0cHM6Ly93d3cua2VzY2kuY29tL2FwcHMvaG9tZS9wcm9qZWN0LzU5ZjZmODhmYzVmM2Y1MTE5NTJjMzBjOQ?x-oss-process=image/format,png)

import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineplt.rcParams["font.sans-serif"] = ["SimHei"]plt.rcParams["axes.unicode_minus"] = Falseplt.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 npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D%matplotlib inlinefig = 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 Axes3Dimport matplotlib.pyplot as pltfig = 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 pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as npxs = 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 pltimport numpy as  npfrom mpl_toolkits.mplot3d import Axes3Dx = 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"] * 2fig = 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 pltfig = 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 variable24 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 of5.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

标签:

最新新闻:

新闻放送
Top