python matplotlib作图

用几个例子来说明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 : DataFrame
x : label or position, default None
y : label or position, default None
Allows plotting of one column versus another
kind : 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 plot
ax : matplotlib axes object, default None
subplots : boolean, default False
Make separate subplots for each column
sharex : boolean, default True if ax is None else False
In 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 False
In case subplots=True, share y axis and set some y axis labels to invisible
layout : tuple (optional)
(rows, columns) for the layout of subplots
figsize : a tuple (width, height) in inches
use_index : boolean, default True
Use index as ticks for x axis
title : string or list
Title 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 lines
legend : False/True/’reverse’
Place legend on axis subplots
style : list or dict
matplotlib line style per column
logx : boolean, default False
Use log scaling on x axis
logy : boolean, default False
Use log scaling on y axis
loglog : boolean, default False
Use log scaling on both x and y axes
xticks : sequence
Values to use for the xticks
yticks : sequence
Values to use for the yticks
xlim : 2-tuple/list
ylim : 2-tuple/list
rot : int, default None
Rotation for ticks (xticks for vertical, yticks for horizontal plots)
fontsize : int, default None
Font size for xticks and yticks
colormap : str or matplotlib colormap object, default None
Colormap to select colors from. If string, load colormap with that name from matplotlib.
colorbar : boolean, optional
If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots)
position : float
Specify 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 plot
table : boolean, Series or DataFrame, default False
If 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 str
See Plotting with Error Bars for detail.
xerr : same types as yerr.
stacked : boolean, default False in line and
bar plots, and True in area plot. If True, create stacked plot.
sort_columns : boolean, default False
Sort column names to determine plot ordering
secondary_y : boolean or sequence, default False
Whether to plot on the secondary y-axis If a list/tuple, which columns to plot on secondary y-axis
mark_right : boolean, default True
When using a secondary_y axis, automatically mark the column labels with “(right)” in the legend
kwds : keywords
Options to pass to matplotlib plotting method
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值