河源市住房和城乡建设局网站,网站seo方法,wordpress 相亲主题,自己写的网站怎么发布Matplotlib 是一个python 的绘图库#xff0c;主要用于生成2D图表。 常用到的是matplotlib中的pyplot#xff0c;导入方式import matplotlib.pyplot as plt 一、显示图表的模式 1.plt.show() 该方式每次都需要手动show()才能显示图表#xff0c;由于pycharm不支持魔法函数主要用于生成2D图表。 常用到的是matplotlib中的pyplot导入方式import matplotlib.pyplot as plt 一、显示图表的模式 1.plt.show() 该方式每次都需要手动show()才能显示图表由于pycharm不支持魔法函数因此在pycharm中都需要采取这种show()的方式。 arr np.random.rand(10)
plt.plot(arr)
plt.show() #每次都需要手动show() 2.魔法函数%matplotlib inline 魔法函数不需要手动show()可直接生成图表但是魔法函数无法在pycharm中使用下面都是在jupyter notebook中演示。 inline方式直接在代码的下方生成一个图表。 %matplotlib inline
x np.random.rand(1000)
y np.random.rand(1000)
plt.scatter(x,y) #最基本散点图
# matplotlib.collections.PathCollection at 0x54b2048 3.魔法函数%matplotlib notebook %matplotlib notebook
s pd.Series(np.random.rand(100))
s.plot(style k--o,figsize (10,5)) notebook方式代码需要运行两次会在代码下方生成一个可交互的图表可对图表进行放大、拖动、返回原样等操作。 4.魔法函数%matplotlib qt5 %matplotlib qt5
plt.gcf().clear()
df pd.DataFrame(np.random.rand(50,2),columns[A,B])
df.hist(figsize(12,5),colorg,alpha0.8) qt5方式会弹出一个独立于界面上的可交互图表。 由于可交互的图表比较占内存运行起来稍显卡因此常采用inline方式。 二、生成图表的方式 1.Seris生成 ts pd.Series(np.random.randn(50),indexpd.date_range(2019/1/1/,periods50))
ts ts.cumsum()
ts.plot() 2.DataFrame生成 df pd.DataFrame(np.random.rand(20,3),columns[A,B,C])
df.plot() 三、图表的基本元素 plot的使用方法以下图表都在%matplotlib inline 模式下生成。 plot(kindline,axNone,figsizeNone,use_indexTrue,titleNone,gridNone,legendNone,\styleNone,logxFalse,logyFalse,loglogFalse,xticksNone,yticksNone,xlimNone,\ylimNone,rotNone,fontsizeNone,colormpapNone,subplotsFalse,tableFalse,xerrNone,yerrNone,\lableNone,secondary_yFalse,**kwargs)
# kind图表类型默认为line折线图其他bar直方图、barh横向直方图
# ax第几个子图
# figsize图表大小即长和宽默认为None指定形式为(m,n)
# use_index是否以原数据的索引作为x轴的刻度标签默认为True如果设置为False则x轴刻度标签为从0开始的整数
# title图表标题默认为None
# grid是否显示网格默认为None也可以直接使用plt.grid()
# legend如果图表包含多个序列序列的注释的位置
# style风格字符串包含了linestyle、color、marker默认为None如果单独指定了color以color的颜色为准
# color颜色默认为None
# xlim和ylimx轴和y轴边界
# xticks和yticksx轴和y轴刻度标签
# rotx轴刻度标签的逆时针旋转角度默认为None例如rot 45表示x轴刻度标签逆时针旋转45°
# fontsizex轴和y轴刻度标签的字体大小
# colormap如果一个图表上显示多列的数据选择颜色族以区分不同的列
# subplots是否分子图显示默认为None如果一个图标上显示多列的数据是否将不同的列拆分到不同的子图上显示
# label图例标签默认为NoneDataFrame格式以列名为label
# alpha透明度 plot()使用方法 图表名称x轴和y轴的名称、边界、刻度、标签等属性。 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df pd.DataFrame(np.random.rand(10,2),columns[A,B])
fig df.plot(figsize(6,4)) #figsize表示图表大小即长和宽
plt.title(test) #图表名称
plt.xlabel(x-axis) #x轴名称
plt.ylabel(y-axis) #y轴名称
plt.legend(loc0) #图表位置
plt.xlim([0,10]) #x轴边界
plt.ylim([0,1]) #y轴边界
plt.xticks(range(1,10)) #x轴刻度间隔
plt.yticks([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]) #y轴刻度间隔
fig.set_xticklabels(%d%i for i in range(1,10)) #x轴显示标签设置显示整数
fig.set_yticklabels(%.2f%i for i in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]) #y轴显示标签设置显示2位小数# legend的loc位置
# 0:best
# 1:upper right
# 2:upper left
# 3:lower left
# 4:lower right
# 5:right
# 6:center left
# 7:center right
# 8:lower center
# 9:upper center
# 10:center 是否显示网格及网格属性、是否显示坐标轴、刻度方向等。 x np.linspace(-np.pi,np.pi,500)
c,s np.cos(x),np.sin(x)
plt.plot(x,c)
plt.plot(x,s)
plt.grid(linestyle --,color gray,linewidth 0.5,axis both) #plt.grid()表示显示网格参数分别表示网格线型、颜色、宽度、显示轴xyboth表示显示x轴和y轴
plt.tick_params(bottomon,topoff,lefton,rightoff) #是否显示刻度默认left和bottom显示import matplotlib
matplotlib.rcParams[xtick.direction]in
matplotlib.rcParams[ytick.direction]in #刻度的显示方向默认为outin表示向内out表示向外inout表示穿透坐标轴内外都有frame plt.gca()
# plt.axis(off) #关闭坐标轴
# frame.axes.get_xaxis().set_visible(False) #x轴不可见
# frame.axes.get_yaxis().set_visible(False) #y轴不可见 linestyle:线型-实线默认--虚线-.一个实线一个点:点 linestyle线型 marker值在x刻度上的显示方式. point marker, pixel markero circle markerv triangle_down marker^ triangle_up marker triangle_left marker triangle_right marker1 tri_down marker2 tri_up marker3 tri_left marker4 tri_right markers square markerp pentagon marker* star markerh hexagon1 markerH hexagon2 marker plus markerx x markerD diamond markerd thin_diamond marker| vline marker_ hline marker markerx刻度上值的显示方式 color颜色rred红色yyello黄色 ggreen绿色bblue蓝色kblack黑色
alpha透明度0-1之间colormap
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, cividis, cividis_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, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r color颜色 也可在创建图表时通过style线型颜色显示方式 例如style -ro表示设置线条为实现、颜色为红色marker为实心圆 使用python内置的风格样式style需导入另外一个模块import matplotlib.style as psl import matplotlib.style as psl
print(psl.available)
psl.use(seaborn)
plt.plot(pd.DataFrame(np.random.rand(20,2),columns[one,two])) 设置主刻度、此刻度、刻度标签显示格式等 from matplotlib.ticker import MultipleLocator,FormatStrFormatter
t np.arange(0,100)
s np.sin(0.1*np.pi*t)*np.exp(-0.01*t)
ax plt.subplot() #不直接在plot中设置刻度
plt.plot(t,s,-go)
plt.grid(linestyle--,colorgray,axisboth)xmajorLocator MultipleLocator(10) #将x主刻度标签设置为10的倍数
xmajorFormatter FormatStrFormatter(%d) #x主刻度的标签显示为整数
xminorLocator MultipleLocator(5) #将x次刻度标签设置为5的倍数
ax.xaxis.set_major_locator(xmajorLocator) #设置x轴主刻度
ax.xaxis.set_major_formatter(xmajorFormatter) #设置x轴主刻度标签的显示格式
ax.xaxis.set_minor_locator(xminorLocator) #设置x轴次刻度
ax.xaxis.grid(whichminor) #设置x轴网格使用次刻度ymajorLocator MultipleLocator(0.5)
ymajorFormatter FormatStrFormatter(%.2f)
yminorLocator MultipleLocator(0.25)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)
ax.yaxis.set_minor_locator(yminorLocator)
ax.yaxis.grid(whichminor)# ax.xaxis.set_major_locator(plt.NullLocator) #删除x轴的主刻度
# ax.xaxis.set_major_formatter(plt.NullFormatter) #删除x轴的标签格式
# ax.yaxis.set_major_locator(plt.NullLocator)
# ax.yaxis.set_major_formatter(plt.NullFormatter) 注释和图表保存 注释plt.text(x轴值,y轴值,注释内容) 水平线plt.axhline(x值) 数值线plt.axvline(y值) 刻度调整plt.axis(equal)设置x轴和y轴每个单位表示的刻度相等 子图位置调整plt.subplots_adjust(leftNone, bottomNone, rightNone, topNone,wspaceNone, hspaceNone)子图距离画板上下左右的距离子图之间的宽度和高度 保存plt.savefig(保存路径及文件名称,dpin,bbox_inchestight,facecolorred,edgecoloryellow) dpi表示分辨率值越大图片越清晰bbox_inches为tight表示尝试剪去图表周围空白部分facecolor为图表背景色默认为白色edgecolor为边框颜色默认为白色。 df pd.DataFrame({A:[1,3,2,6,5,8,5,9],B:[7,2,6,4,8,5,4,3]})
df.plot()
plt.text(2,6,^_^,fontsize12)
plt.savefig(rC:\Users\penghuanhuan\Desktop\haha.png,dpi400,bbox_inchestight,facecolorred,edgecoloryellow)
print(finished) 四、图表各对象 figure相当于一块画板ax是画板中的图表一个figure画板中可以有多个图表。 创建figure对象 plt.figure(numNone, figsizeNone, dpiNone, facecolorNone, edgecolorNone, frameonTrue, FigureClassFigure, clearFalse, **kwargs ) 如果不设置figure对象在调用plot时会自动生成一个并且生成其中的一个子图且所有plot生成的图表都显示在一个图表上面。 num指定为画板中的第几个图表在同一段代码中相同figure对象的不同num各自生成一个图表相同figure对象的相同num和不同figure对象的相同num均生成在一个图标上。 figsize图表的大小即长和宽元组形式(m,n) dpi分辨率 1.创建子图方法1 ①通过plt生成figure对象 ②通过figure对象的add_subplot(m,n,p)创建子图表示生成m*n个子图并选择第p个子图子图的顺序由左到右由上到下 ③在子图上绘制图表 #子图
fig plt.figure(figsize (8,4),facecolor lightgray) #创建figure对象ax1 fig.add_subplot(2,2,1) #创建一个2*2即4个子图并选择第1个子图参数也可以直接写成221# ax1 plt.subplot(2,2,1) 也可以使用这种方式添加子图
plt.plot(np.random.rand(20),k--) #在子图上1绘制图表
plt.plot(np.random.rand(20),b--) #在子图上1绘制图表
# ax1.plot(np.random.rand(20),b--)ax2 fig.add_subplot(2,2,3) #选择第3个子图
ax2.scatter(np.random.rand(100),np.random.rand(100)) #在子图上3绘制图表ax3 fig.add_subplot(2,2,2) #选择第2个子图
ax3.hist(np.random.rand(20))ax4 fig.add_subplot(2,2,4) #选择第4个子图
ax4.plot(pd.DataFrame(np.random.rand(10,2),columns [A,B])) 通过figure对象添加子图 2.创建子图方法2 ①通过plt的subplots(m,n)方法生成一个figure对象和一个表示figure对象m*n个子图的二维数组 ②通过二维数组选择子图并在子图上绘制图表 fig,axes plt.subplots(2,3,figsize (10,6)) #生成一个figure对象和一个2*3的二维数组数组元素为子图对象
#subplots方法还有参数sharex和sharey表示是否共享x轴和y轴默认为False
print(fig,type(fig)) #figure对象
print(axes,type(axes))ax1 axes[0][1] #表示选择第1行第2个子图
ax1.plot(np.random.rand(20))ax2 axes[1,0] #表示选择第2行第1个子图
ax2.plot(np.arange(10))plt.subplots_adjust(wspace0.2,hspace0.3) #调整子图之间的间隔宽、间隔高占比 通过subplots添加子图 3.子图的创建方法3 在创建plot的时候添加参数subplotTrue即可 df.plot(style--ro,subplotsTrue,figsize(10,8),layout(2,2),sharexFalse,shareyTrue) subplots默认为False在一张图表上显示True则会拆分为子图 layout子图的排列方式即几行几列 sharex默认为True sharey默认为False df pd.DataFrame(np.random.rand(100,4))
df.plot(style--ro)
df.plot(style--ro,subplotsTrue,figsize(10,8),layout(2,2),sharexFalse,shareyTrue) 显示汉字问题请参考https://www.cnblogs.com/kuxingseng95/p/10021788.html 转载于:https://www.cnblogs.com/Forever77/p/11299813.html