matplotlib.pyplot 小结

                                          matplotlib.pyplot 小结

一、数据为列表

#coding:UTF-8

#matplotlib.pyplot是一组命令样式函数,使matplotlib像MATLAB一样工作。
import matplotlib.pyplot as plt   
import numpy as np

#如果为plot()命令提供单个列表或数组 ,matplotlib假定它是一系列y值,并自动为您生成x值。
#由于python范围以0开头,因此默认的x向量与y的长度相同,但以0开头。
plt.subplot(221)
plt.plot([1, 2, 3, 4])   #x数据为 [0,1,2,3]
plt.ylabel('some numbers')  #y轴标签


plt.subplot(222)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])  #x数据为 [0,1,2,3]  y数据为 [1,4,9,16]


plt.subplot(223)
#对于每对x,y对的参数,有一个可选的第三个参数,它是指示绘图的颜色和线型的格式字符串。
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
# axis()命令采用列表并指定轴的视口。[xmin, xmax, ymin, ymax]
plt.axis([0, 6, 0, 20])


#如果matplotlib仅限于使用列表,那么数字处理将毫无用处。通常,使用numpy数组 所有序列都在内部转换为numpy数组。
plt.subplot(224)
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes,红色破折号 blue squares 蓝色方块 and green triangles 绿色的三角
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

二、用关键字字符串绘图

#@@@@@@用关键字字符串绘图

#在某些情况下,您可以使用允许您使用字符串访问特定变量的格式的数据。
#例如,用 numpy.recarray或pandas.DataFrame  Matplotlib允许您使用data关键字参数提供此类对象
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()

三、用分类变量绘图 

#@@@@@@用分类变量绘图

#也可以使用分类变量创建绘图。Matplotlib允许您将分类变量直接传递给许多绘图函数。
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(figsize=(9, 3))
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

四、使用多个图形和轴

#@@@@@@使用多个图形和轴

#并且pyplot,具有当前图形和当前轴的概念。所有绘图命令都适用于当前轴。该函数gca()返回当前轴(matplotlib.axes.Axes实例),
#并 gcf()返回当前图形(matplotlib.figure.Figure实例)。
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()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

五、使用文本 

#@@@@@@使用文本

#该text()命令可用于在任意位置添加文本xlabel(), ylabel()并title() 用于在指定位置添加文本
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', alpha=0.75)

plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
#所有text()命令都返回一个 matplotlib.text.Text实例。
#与上面的行一样,您可以通过将关键字参数传递到文本函数或使用setp()以下内容来自定义属性:
#t = plt.xlabel('my data', fontsize=14, color='red')

六、注释文本 

#@@@@@@注释文本

#text()上面基本命令的使用将文本放在Axes上的任意位置。文本的常见用途是注释绘图的某些功能,并且该 annotate()方法提供帮助功能以使注释变得容易。
#在注释中,有两点需要考虑:注释的位置由参数xy和文本的位置表示xytext。这两个参数都是(x,y)元组。
#xy(箭头提示)和xytext 位置(文本位置)都在数据坐标中。可以选择各种其他坐标系 
plt.figure()
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05),
             )

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

七、 线性轴刻度,还支持对数和logit刻度

#@@@@@@matplotlib.pyplot不仅支持线性轴刻度,还支持对数和logit刻度。

#如果数据跨越许多数量级,则通常使用此方法。更改轴的比例很容易
from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the 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', linthreshy=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)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# 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()

八、对图像进行处理 

#coding:UTF-8
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

plt.subplot(2,3,1)
img = mpimg.imread('008.png')   #读取图片
#print(img)
imgplot = plt.imshow(img) 


plt.subplot(2,3,2)
lum_img = img[:, :, 0]  #数组切片
plt.imshow(lum_img)


plt.subplot(2,3,3)
plt.imshow(lum_img, cmap="hot")


plt.subplot(2,3,4)
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('nipy_spectral')

plt.subplot(2,3,5)
imgplot = plt.imshow(lum_img)
plt.colorbar()


plt.subplot(2,3,6)
plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
plt.show()

imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
plt.show()

发布了443 篇原创文章 · 获赞 656 · 访问量 60万+

猜你喜欢

转载自blog.csdn.net/LiuJiuXiaoShiTou/article/details/100159994