Matplotlib学习(2)Pyplot tutorial(Pyplot 教程)

解释一下API的概念:application programming interface ,应用程序接口,用来提供应用程序与开发人员基于某软件或者硬件得以访问的一组例程,而又无需访问源代码或理解内部工作机制的细节。

1.Intro to pyplot( Pyplot入门)

matplotlib.pyplot时一组函数的集合,这些函数使matplotlib像MATLAB一样工作,每个pyplot函数都makes some change to a figure。
例子1:

import numpy as np
import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16],'--')#plot是一个多用途的函数,可以接受任意数量的参数。例如,对于x和y,可以这样写。
plt.ylabel('square')
plt.xlabel('some numbers')
plt.axis([0,5,0,18])#分别是x和y的坐标轴的范围
plt.show()


例子2:对numpy.arange绘图操作:

import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0.,5.,0.2)
plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')#plot是一个多用途的函数,可以接受任意数量的参数。
plt.show()

1

2.使用关键字字符串进行绘图

There are some instances where you have data in a format that lets you access particular variables with strings. For example, with numpy.recarray or pandas.DataFrame.
某些情况下,允许使用字符串访问特定的变量,比如numpy.recarray或者pandas.
Matplotlib allows you provide such an object with the data keyword argument. If provided, then you may generate plots with the strings corresponding to these variables.
允许您使用data关键字参数提供这样的对象,如果提供了,那么就可以生成包含这些变量对应的字符串的绘图。
例子:

import numpy as np
import matplotlib.pyplot as plt
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

在这里插入图片描述

3.用范畴变量绘图

It is also possible to create a plot using categorical variables. Matplotlib allows you to pass categorical variables directly to many plotting functions.
Matplotlib允许直接将范畴变量传递给许多绘图函数
例如:

import numpy as np
import matplotlib.pyplot as plt
names=['group_a','group_b','group_c']
values=[1,10,100]
#参数说明:num用来区分画布,可以通过plt.figure(num='fig1')之后的操作来给画布'fig1'画图
# figsize:以inches英寸为单位的宽高,一英寸等于2.54cm
#dpi:图形分辨率,facecolor背景色,edgecolor边框色,
#frameon默认值True为绘制边框,False则不绘制边框
#FigureClass派生类,从派生类创建figure实例
#clear:重建figure实例
plt.figure(num="fig1",figsize=(9,6),dpi=None,facecolor='None',edgecolor='yellow',frameon=False)
plt.subplot(1,3,1)#把画布分成1*3的格子,把接下的图放在第1格。逗号可有可无。
plt.bar(names,values,color='b',alpha=0.8)#柱状图
plt.subplot(132)#把画布分成1*3的格子,把接下的图放在第2格。逗号可有可无。
plt.scatter(names,values,color='r',alpha=0.9)#散点图
plt.subplot(133)
plt.plot(names,values,linewidth=2.0,alpha=0.9,color='g')#linewidth是线条粗细,alpha用来调节透明度
plt.suptitle("Jiajianghao's Categorical Plotting")
plt.show()

注意,plt.figure()中的参数我只是罗列了一些方便了解,实际上绘图时用到哪个添加哪个即可,函数有自带的默认值,没必要每个参数都设值。

4.Controlling line properties(控制行属性)

Lines have many attributes that you can set: linewidth, dash style, antialiased, etc; see Matplotlib.lines.Line2D. There are several ways to set line properties.

Lines有许多可以设置的属性.

Use setp. The example below uses a MATLAB-style function to set multiple properties on a list of lines. setp works transparently with a list of objects or a single object. You can either use python keyword arguments or MATLAB-style string/value pairs

对于对象列表或者单个对象,step可以透明地工作:
例子:

import numpy as np
import matplotlib.pyplot as plt
x1=[1,2,3,4]
y1=[4,5,6,7]
x2=[4,5]
y2=[7,8,]
lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
plt.show()


一些可以用的Line 2D属性
在这里插入图片描述

5.Working with multiple figures and axes

MATLAB 和 pyplot 具有当前图形figure和当前轴axes的概念。所有绘图函数都应用于当前轴。函数 gca 返回当前轴(matplotlib.axes) ,gcf 返回当前图(matplotlib.figure)。图例)。通常情况下,您不必担心这个问题,因为这些都是在幕后处理的。下面是一个创建两个subplots的脚本:

import numpy as np
import matplotlib.pyplot as plt
def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)

t1=np.arange(0.0,5.0,0.1)
t2=np.arange(0.0,5.0,0.02)

plt.figure(figsize=(10,5))
plt.subplot(121)
plt.plot(t1, f(t1),'bo',t2,f(t2),'y')
plt.subplot(122)
plt.plot(t2,np.cos(2*np.pi*t2),'r--')
plt.suptitle("Jiajianghao's plotting")
plt.show()

在这里插入图片描述

6.Working with text

matplotlib.pyplot.text()可以在指定的位置添加文本,而xlabel、ylabel,title只能用于指定位置添加文本。

import numpy as np
import matplotlib.pyplot as plt
mu,sigma=100,15
x=mu+sigma*np.random.randn(10000)

#the histogram of the data
n,bins,patches=plt.hist(x,50,density=1,facecolor='g')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\sigma_i=15$')
plt.text(60, .025, r'$\mu=100,\sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

在这里插入图片描述
Annotating text 注解文本:

import numpy as np
import matplotlib.pyplot as plt
ax = plt.subplot(111)

t = np.arange(0.0, 6.28, 0.01)
s = np.cos(t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local min', xy=(3, -1), xytext=(4, 0.5),#xy=()是箭头指向的位置坐标,xytext()是箭尾的坐标
             arrowprops=dict(facecolor='black', shrink=0.05),
             )

plt.ylim(-2, 2)
plt.show()

在这里插入图片描述

7.Logarithmic and other nonlinear axes (对数轴和其他非线性轴)

例子:`

import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the open interval (0, 1)
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure()

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)

# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)

# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值