python matplotlib作图

来源:互联网 发布:联合办公 知乎 编辑:程序博客网 时间:2024/05/17 08:53

用几个例子来说明matplotlib的用法

Example 1.

# coding:utf-8                                                                                                                       import matplotlib.pyplot as plt                                                                                                      import numpy as np                                                                                                                   array1 = np.random.rand(100)                                                                                                         array2 = np.random.rand(100)                                                                                                         fig1 = plt.figure(1)                                           # 创建一个Figure                                                          ax1 = fig1.add_subplot(1,1,1)                                  # add_subplot()创建一个子图或多个子图                                            ax1.plot(array1, 'o-', color = 'blue', label = 'array1')       # label设置标签,'o-'代表线型                                                           ax1.plot(array2, '>-', color = 'red', label = 'array1')                                                                              ax1.set_xscale('log')                                          # 设置x轴为对数坐标                                                           ax1.set_yscale('log')                                          # 设置y轴为对数坐标                                                           ax1.set_xlabel('x',fontsize = 15)                              # 设置x轴的标签, fontsize设置字体大小                                             ax1.set_ylabel('y', fontsize = 15)                             # 设置y轴的标签, fontsize设置字体大小                                             ax1.set_xlim(0,100)                                            # 设置x轴范围                                                              ax1.set_ylim(0,1)                                              # 设置y轴范围                                                              ax1.set_xticks([1,2,3,4,5,6,7,8,9,10,20,30,40,50,100])         # 设置x轴要显示的刻度                                                          ax1.set_xticklabels(['a','b','c','d',5,6,7,8,9,10,20,30,40,50,100]) # 设置该刻度上的标签                                                      ax1.grid(True, which='major', axis='both')                      # 设置网格                                                               ax1.legend(loc = 'best', numpoints = 1)                         # 图例, loc='best',即图例放在最不碍事的位置,numpoint图例上自由一个点                       plt.show()                                                                                                                                                                         

这里写图片描述
Example 2.

# coding:utf-8                                                                                                           import matplotlib.pyplot as plt                                                                                          import numpy as np                                                                                                       import pandas as pd                                                                                                      #                                                                                                                        df1 = pd.DataFrame(np.random.rand(25), index=np.arange(25), columns=['test1'])                                           df2 = pd.DataFrame(np.random.rand(25), index=np.arange(25), columns=['test2'])                                           df3 = pd.DataFrame(np.random.rand(25), index=np.arange(25), columns=['test3'])                                           df4 = pd.DataFrame(np.random.rand(25), index=np.arange(25), columns=['test4'])                                           # 生成4个子图                                                                                                                 fig = plt.figure(1)                                                                                                      ax1 = fig.add_subplot(2,2,1)                                                                                             ax2 = fig.add_subplot(2,2,2)                                                                                             ax3 = fig.add_subplot(2,2,3)                                                                                             ax4 = fig.add_subplot(2,2,4)                                                                                                                                                                        #------ df.plot参数 ---------#                  df1.plot(ax = ax1, style = 'b*-', kind = 'line', rot = 360, grid = 'on')   # style设置线型(ko--)                             ax1.set_xticks(range(0,26,5))                                              # alpha设置不透明度                                 ax1.set_xticklabels(range(0,26,5))                                         # kind可以是'line','bar','barh','kde'                                                                                       # logy 在y轴使用对数标尺                              df2.plot(ax = ax2, kind = 'line', logy = True, title = 'test2', rot = 270) # xlim x轴的界限                                  ax2.set_xticks(range(0,26,5))                                              # ylim y轴的界限                                  ax2.set_xticklabels(range(0,26,5))                                         # grid 网格线                                                                                                               # rot旋转坐标刻度标签                                 df3.plot(ax = ax3, kind = 'line', title = 'test3', rot = 180, sharex = True)# title 图像标题                                 ax3.set_xticks(range(0,26,5))                                              # figsiez 图像大小                                ax3.set_xticklabels(range(0,26,5))                                         # sharex/sharex 共用x轴/y轴                       df4.plot(ax = ax4, style = 'ko--', kind = 'line', title = 'test4', rot = 90, figsize = (8,10))                           ax4.set_xticks(range(0,26,5))                                                                                            ax4.set_xticklabels(range(0,26,5))                                                                                       plt.show()                                                                                                                                                                                                                                   

这里写图片描述

df.plot()参数说明

```df.plot(kind='line')Parameters: data : DataFramex : label or position, default Noney : label or position, default NoneAllows plotting of one column versus anotherkind : str‘line’ : line plot (default)‘bar’ : vertical bar plot‘barh’ : horizontal bar plot‘hist’ : histogram‘box’ : boxplot‘kde’ : Kernel Density Estimation plot‘density’ : same as ‘kde’‘area’ : area plot‘pie’ : pie plot‘scatter’ : scatter plot‘hexbin’ : hexbin plotax : matplotlib axes object, default Nonesubplots : boolean, default FalseMake separate subplots for each columnsharex : boolean, default True if ax is None else FalseIn case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure!sharey : boolean, default FalseIn case subplots=True, share y axis and set some y axis labels to invisiblelayout : tuple (optional)(rows, columns) for the layout of subplotsfigsize : a tuple (width, height) in inchesuse_index : boolean, default TrueUse index as ticks for x axistitle : string or listTitle to use for the plot. If a string is passed, print the string at the top of the figure. If a list is passed and subplots is True, print each item in the list above the corresponding subplot.grid : boolean, default None (matlab style default)Axis grid lineslegend : False/True/’reverse’Place legend on axis subplotsstyle : list or dictmatplotlib line style per columnlogx : boolean, default FalseUse log scaling on x axislogy : boolean, default FalseUse log scaling on y axisloglog : boolean, default FalseUse log scaling on both x and y axesxticks : sequenceValues to use for the xticksyticks : sequenceValues to use for the yticksxlim : 2-tuple/listylim : 2-tuple/listrot : int, default NoneRotation for ticks (xticks for vertical, yticks for horizontal plots)fontsize : int, default NoneFont size for xticks and ytickscolormap : str or matplotlib colormap object, default NoneColormap to select colors from. If string, load colormap with that name from matplotlib.colorbar : boolean, optionalIf True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots)position : floatSpecify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)layout : tuple (optional)(rows, columns) for the layout of the plottable : boolean, Series or DataFrame, default FalseIf True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib’s default layout. If a Series or DataFrame is passed, use passed data to draw a table.yerr : DataFrame, Series, array-like, dict and strSee Plotting with Error Bars for detail.xerr : same types as yerr.stacked : boolean, default False in line andbar plots, and True in area plot. If True, create stacked plot.sort_columns : boolean, default FalseSort column names to determine plot orderingsecondary_y : boolean or sequence, default FalseWhether to plot on the secondary y-axis If a list/tuple, which columns to plot on secondary y-axismark_right : boolean, default TrueWhen using a secondary_y axis, automatically mark the column labels with “(right)” in the legendkwds : keywordsOptions to pass to matplotlib plotting method
原创粉丝点击