Pyplot tutorial (Pyplot入门)
An introduction to the pyplot interface.
Intro to pyplot (介绍pyplot)
用Pyplot可以很快的生成可视化图例
import matplotlib.pyplot as plt
import numpy as np
plt.plot([1, 2, 3, 4]) #一个数组,也可以用numpy生成
#a = np.arrange(1,5)
#plt.plot(a)
plt.ylabel('some numbers') # 纵坐标图例
plt.show() #显示出来
生成x和y的关系图
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4],[1, 4, 9, 16]) #一个数组,也可以用numpy生成
plt.show() #显示出来
Formatting the style of your plot (生成你的图例)
画个折线图
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 6, 9, 16], 'ro') # 红点
plt.axis([0, 6, 0, 20]) # [xmin, xmax, ymin, ymax]
plt.show()
结合numpy
import matplotlib.pyplot as plt
import numpy as np
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()
Plotting with keyword strings(用关键词绘图)
import matplotlib.pyplot as plt
import numpy as np
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)
} # 创建一个字典data
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() # 每次运行代码出来的散点图都不一样
Plotting with categorical variables
import matplotlib.pyplot as plt
import numpy as np
names = ['a','b','c']
value = [1,10,100]
plt.figure(figsize=(9,3)) # 指定创建画布的大小
plt.subplot(131) # 将画布设置为一行三列的子图网格,绘图焦点设置在第一个网格
plt.bar(names,value) # 第一个网格画柱状图
plt.subplot(132)
plt.scatter(names,value) # 第二个网格画散点图
plt.subplot(133)
plt.plot(names,value) # 第三个网格画折线图
plt.suptitle('Categorical Plotting') # 标题
plt.show()
Working with multiple figures and axes
import matplotlib.pyplot as plt
import numpy as np
def f(t):
return np.exp(-t) * np.cos(2 * np.pi * t)
t1 = np.arange(0.0, 5.0, 0.1) # 从0到5,每隔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') # 这个参数我去查了matplotlib.org 上面找到了对应API的参数在下面
# bo 即蓝色圆圈,k就是黑色
plt.subplot(212)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--') #r--即红色虚线
plt.show()
Markers
character | description |
---|---|
'.' | point marker |
',' | pixel marker |
'o' | circle marker |
'v' | triangle_down marker |
'^' | triangle_up marker |
'<' | triangle_left marker |
'>' | triangle_right marker |
'1' | tri_down marker |
'2' | tri_up marker |
'3' | tri_left marker |
'4' | tri_right marker |
'8' | octagon marker |
's' | square marker |
'p' | pentagon marker |
'P' | plus (filled) marker |
'*' | star marker |
'h' | hexagon1 marker |
'H' | hexagon2 marker |
'+' | plus marker |
'x' | x marker |
'X' | x (filled) marker |
'D' | diamond marker |
'd' | thin_diamond marker |
`’ | '` |
'_' | hline marker |
Line Styles
character | description |
---|---|
'-' | solid line style |
'--' | dashed line style |
'-.' | dash-dot line style |
':' | dotted line style |
Example format strings:
'b' # blue markers with default shape
'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line
Colors
The supported color abbreviations are the single letter codes
character | color |
---|---|
'b' | blue |
'g' | green |
'r' | red |
'c' | cyan |
'm' | magenta |
'y' | yellow |
'k' | black |
'w' | white |
Working with text
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75)
plt.xlabel('Smarts',fontsize =14, color = 'red') # 可以指定text大小颜色
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.axis([X_min, X_max, Y_min, Y_max])
plt.grid(True)
plt.show()
-
plt.hist()是matplotlib库中用于绘制直方图的函数:
plt.hist(x, bins=None, range=None, density=False, histtype=‘bar’, color=None, label=None)
x
:输入的数据,通常是一个一维数组或类似数组的对象。bins
:指定直方图的区间数量或区间的边界。可以是整数(区间数量)或包含边界值的数组。默认为10。range
:指定数据的范围,超出这个范围的数据会被忽略。density
:如果设置为True,则直方图的高度将被标准化,以表示概率密度而不是计数。默认为False。histtype
:指定绘制的直方图类型,可以是’bar’(普通的柱状直方图)或’step’(阶梯状直方图)。color
:设置柱子的颜色。label
:用于标记该直方图的标签,以便添加图例。alpla
:设置透明度,其中0表示完全透明(不可见),1表示完全不透明。
Using mathematical expressions in text
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.text(),在指定位置添加指定text,可以用数学表达式- r的作用,不让编译器将数学表达式里面的反斜杠视为python的转义字符
Annotating text (注释)
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111)
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) # 设置y的极限
plt.show()
matplotlib.pyplot.annotat()
matplotlib.pyplot.annotate(
text, # 注释的文本内容
xy=(x, y), # 要注释的点的坐标
xytext=(x_text, y_text), # 注释文本的坐标
arrowprops=dict(), # 箭头的可选属性(如果使用箭头)
**kwargs # 其他用于文本格式化的可选关键字参数
)
Logarithmic and other nonlinear axes
import matplotlib.pyplot as plt
import numpy as np
# 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()
除了线性的图表,**matplotlib.pyplot
**也可以生成对数图样和其他的非线性图样
总结
以上内容基本上来自matplotlib中文网和官网,加上了自己学习过程中的一些注释,希望有点帮助