您的位置:首页 > 编程语言 > PHP开发

基于matplotlib的数据可视化 - 笔记

2018-07-24 23:32 796 查看

1 基本绘图

在plot()函数中只有x,y两个量时。

import numpy as np
import matplotlib.pyplot as plt

# 生成曲线上各个点的x,y坐标,然后用一段段直线连起来
# 利用linspace函数产生一个等差数列
x = np.linspace(-np.pi, np.pi, 200)

cos_y = np.cos(x) / 2
sin_y = np.sin(x)

# 用直线连接曲线上各点
plt.plot(x, cos_y)
plt.plot(x, sin_y)

# 显示图形
plt.show()


Help on function scatter in module matplotlib.pyplot:

scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
A scatter plot of *y* vs *x* with varying marker size and/or color.

Parameters
----------
x, y : array_like, shape (n, )
The data positions.

s : scalar or array_like, shape (n, ), optional
The marker size in points**2.
Default is ``rcParams['lines.markersize'] ** 2``.

c : color, sequence, or sequence of color, optional, default: 'b'
The marker color. Possible values:

- A single color format string.
- A sequence of color specifications of length n.
- A sequence of n numbers to be mapped to colors using *cmap* and
*norm*.
- A 2-D array in which the rows are RGB or RGBA.

Note that *c* should not be a single numeric RGB or RGBA sequence
because that is indistinguishable from an array of values to be
colormapped. If you want to specify the same RGB or RGBA value for
all points, use a 2-D array with a single row.

marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
The marker style. *marker* can be either an instance of the class
or the text shorthand for a particular marker.
See `~matplotlib.markers` for more information marker styles.

cmap : `~matplotlib.colors.Colormap`, optional, default: None
A `.Colormap` instance or registered colormap name. *cmap* is only
used if *c* is an array of floats. If ``None``, defaults to rc
``image.cmap``.

norm : `~matplotlib.colors.Normalize`, optional, default: None
A `.Normalize` instance is used to scale luminance data to 0, 1.
*norm* is only used if *c* is an array of floats. If *None*, use
the default `.colors.Normalize`.

vmin, vmax : scalar, optional, default: None
*vmin* and *vmax* are used in conjunction with *norm* to normalize
luminance data. If None, the respective min and max of the color
array is used. *vmin* and *vmax* are ignored if you pass a *norm*
instance.

alpha : scalar, optional, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).

linewidths : scalar or array_like, optional, default: None
The linewidth of the marker edges. Note: The default *edgecolors*
is 'face'. You may want to change this as well.
If *None*, defaults to rcParams ``lines.linewidth``.

verts : sequence of (x, y), optional
If *marker* is *None*, these vertices will be used to construct
the marker.  The center of the marker is located at (0, 0) in
normalized units.  The overall marker is rescaled by *s*.

edgecolors : color or sequence of color, optional, default: 'face'
The edge color of the marker. Possible values:

- 'face': The edge color will always be the same as the face color.
- 'none': No patch boundary will be drawn.
- A matplotib color.

For non-filled markers, the *edgecolors* kwarg is ignored and
forced to 'face' internally.

Returns
-------
paths : `~matplotlib.collections.PathCollection`

Other Parameters
----------------
**kwargs : `~matplotlib.collections.Collection` properties

See Also
--------
plot : To plot scatter plots when markers are identical in size and
color.

Notes
-----

* The `.plot` function will be faster for scatterplots where markers
don't vary in size or color.

* Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which
case all masks will be combined and only unmasked points will be
plotted.

* Fundamentally, scatter works with 1-D arrays; *x*, *y*, *s*, and *c*
may be input as 2-D arrays, but within scatter they will be
flattened. The exception is *c*, which will be flattened only if its
size matches the size of *x* and *y*.

.. note::
In addition to the above described arguments, this function can take a
**data** keyword argument. If such a **data** argument is given, the
following arguments are replaced by **data[<arg>]**:

* All arguments with the following names: 'c', 'color', 'edgecolors', 'facecolor', 'facecolors', 'linewidths', 's', 'x', 'y'.


help(plt.scatter)
查看参数可知,其可以设置一个值,表示所有点的属性均统一为该值,也可通过array_like为每一个散点分配属性值。

具体属性值可查看帮助文档,此不枚举细列。

5.2 示例一

mport numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi*1.5,np.pi*1.5,200)
sin_y = np.sin(x)
cos_y = np.cos(x)

# 计算特殊点的坐标
xo = np.pi * 3 / 4
sin_yo = np.sin(xo)
cos_yo = np.cos(xo)

plt.plot(x, sin_y, linestyle='--', linewidth=1,color='dodgerblue')
plt.plot(x, cos_y, linestyle=':', linewidth=1.2,color='orangered')

# 绘制特殊点
# plot(x,y)绘制一条线,x值[xo,xo],y值[cos_yo,sin_yo],
# 实际上将两个坐标点(xo, cos_yo), (xo, sin_yo)连接起来
plt.plot([xo, xo], [cos_yo, sin_yo],
linestyle='--',color='limegreen')
# 绘制
plt.scatter([xo, xo], [cos_yo, sin_yo],
s=60,edgecolor='limegreen',
facecolor='white',zorder=10)
# 显示图形
plt.show()




5.3 示例2

import numpy as np
import matplotlib.pyplot as plt

n = 10000
# 产生均值为0标准差为1区间的n个服从正态分布的随机数
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)

# 获取颜色的分布对应值
c_color = np.sqrt(x**2 + y**2)
print(d)
plt.figure('Scatter', facecolor='lightgray')
plt.title('Scatter', fontsize=20)
plt.xlabel('x', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.tick_params(labelsize=10)
plt.grid(linestyle=':')
plt.scatter(x, y, s=60, c=c_color, cmap='jet_r', alpha=0.5)

plt.show()




6 图中添加注释annotate

对点 xy 进行文本注释

plt.annotate(
'注释文本',字符串str
xy=被注释点的坐标,序列,数组,可迭代对象iterable
xycoords=被注释点的坐标属性,相对位置,有每一个属性值对应位置描述
xytext=注释文本的坐标,若无,则默认xy坐标点
textcoords=注释文本坐标的属性,
fontsize=字体大小,
arrowprops=dict(arrowstyle=箭头形状,connectionstyle=箭头连线的风格)
)


内容较多,可查看帮助文档

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi*1.5,np.pi*1.5,200)
sin_y = np.sin(x)
cos_y = np.cos(x)

# 计算特殊点的坐标
xo = np.pi * 3 / 4
sin_yo = np.sin(xo)
cos_yo = np.cos(xo)

plt.plot(x, sin_y, linestyle='--', linewidth=1,color='dodgerblue')
plt.plot(x, cos_y, linestyle=':', linewidth=1.2,color='orangered')

# 绘制特殊点
# plot(x,y)绘制一条线,x值[xo,xo],y值[cos_yo,sin_yo],
# 实际上将两个坐标点(xo, cos_yo), (xo, sin_yo)连接起来
plt.plot([xo, xo], [cos_yo, sin_yo],
linestyle='--',color='limegreen')
# 绘制
plt.scatter([xo, xo], [cos_yo, sin_yo],
s=60,edgecolor='limegreen',
facecolor='white',zorder=10)

# 添加注释
plt.annotate(
r'$cos(\frac{3\pi}{4})=-\frac{\sqrt{2}}{2}$',
xy=(xo, cos_yo), xycoords='data',
xytext=(-90, -40), textcoords='offset points',
fontsize=14, arrowprops=dict(
arrowstyle='->', connectionstyle='arc3, rad=0.2'))

plt.annotate(
r'$sin(\frac{3\pi}{4})=\frac{\sqrt{2}}{2}$',
xy=(xo, sin_yo), xycoords='data',
xytext=(20, 20), textcoords='offset points',
fontsize=14, arrowprops=dict(
arrowstyle='->', connectionstyle='arc3, rad=0'))

# 显示图形
plt.show()




7 实例

生成如下图的代码



import numpy as np
import matplotlib.pyplot as plt

# 生成曲线上各个点的x,y坐标,然后用一段段直线连起来
x = np.linspace(-np.pi, np.pi, 200)  # 产生一个等差数列

cos_y = np.cos(x) / 2
sin_y = np.sin(x)

# 计算特殊点的坐标
xo = np.pi * 3 / 4
yo_cos = np.cos(xo) / 2
yo_sin = np.sin(xo)

# 设置坐标范围
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(min(cos_y.min(), sin_y.min()) * 1.1,
max(cos_y.max(), sin_y.max()) * 1.1)

# 设置坐标轴刻度标签
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'0',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'])

# plt.yticks([])
plt.yticks([-1, -0.5, 0.5, 1])

# 将矩形坐标轴改成十字坐标轴:
# 获取当前坐标轴对象
ax = plt.gca()  # get current axis

# 将垂直坐标刻度置于左边框
ax.yaxis.set_ticks_position('left')

# 将左边框置于数据坐标原点
ax.spines['left'].set_position(('data', 0))

# 将水平坐标刻度置于底边框
ax.xaxis.set_ticks_position('bottom')

# 将底边框置于数据坐标原点
ax.spines['bottom'].set_position(('data', 0))

# 将右边框和顶边框设置成无色
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 用直线连接曲线上各点
plt.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue', label=r'$y=\frac{1}{2}cos(x)$')
plt.plot(x, sin_y, linestyle=':', linewidth=1.2,
color='orangered', label=r'$y=sin(x)$')

# 绘制特殊点
plt.plot([xo, xo], [yo_cos, yo_sin], linestyle='--',
linewidth=1, color='limegreen')
plt.scatter([xo, xo], [yo_cos, yo_sin], s=60,
edgecolor='limegreen', facecolor='white',
zorder=3)

# 添加注释
plt.annotate(
r'$\frac{1}{2}cos(\frac{3\pi}{4})=-\frac{\sqrt{2}}{2}$',
xy=(xo, yo_cos), xycoords='data',
xytext=(-90, -40), textcoords='offset points',
fontsize=14, arrowprops=dict(
arrowstyle='->', connectionstyle='arc3, rad=0.2'))

plt.annotate(
r'$sin(\frac{3\pi}{4})=\frac{\sqrt{2}}{2}$',
xy=(xo, yo_sin), xycoords='data',
xytext=(20, 20), textcoords='offset points',
fontsize=14, arrowprops=dict(
arrowstyle='->', connectionstyle='arc3, rad=0'))

plt.legend(loc='upper left')

# 显示图形
plt.show()


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: