python绘制散点图,⾮常全,⾮常详细(已验证)少废话,直接上代码
1import matplotlib.pyplot as plt
2import numpy as np
3# 1. ⾸先是导⼊包,创建数据
4n = 10
5x = np.random.rand(n) * 2# 随机产⽣10个0~2之间的x坐标
6y = np.random.rand(n) * 2# 随机产⽣10个0~2之间的y坐标
7# 2.创建⼀张figure
8fig = plt.figure(1)
9# 3. 设置颜⾊ color 值【可选参数,即可填可不填】,⽅式有⼏种
10# colors = np.random.rand(n) # 随机产⽣10个0~1之间的颜⾊值,或者
11colors = ['r', 'g', 'y', 'b', 'r', 'c', 'g', 'b', 'k', 'm']  # 可设置随机数取
12# 4. 设置点的⾯积⼤⼩ area 值【可选参数】
13area = 20*np.arange(1, n+1)
14# 5. 设置点的边界线宽度【可选参数】
15widths = np.arange(n)# 0-9的数字
16# 6. 正式绘制散点图:scatter
17plt.scatter(x, y, s=area, c=colors, linewidths=widths, alpha=0.5, marker='o')
18# 7. 设置轴标签:xlabel、ylabel
19#设置X轴标签
20plt.xlabel('X坐标')
21#设置Y轴标签
22plt.ylabel('Y坐标')
23# 8. 设置图标题:title
24plt.title('test绘图函数')
25# 9. 设置轴的上下限显⽰值:xlim、ylim
26# 设置横轴的上下限值
27plt.xlim(-0.5, 2.5)
28# 设置纵轴的上下限值
29plt.ylim(-0.5, 2.5)
30# 10. 设置轴的刻度值:xticks、yticks
31# 设置横轴精准刻度
33# 设置纵轴精准刻度
35# 也可按照xlim和ylim来设置
36# 设置横轴精准刻度
38# 设置纵轴精准刻度
40
41# 11. 在图中某些点上(位置)显⽰标签:annotate
42# plt.annotate("(" + str(round(x[2], 2)) + ", " + str(round(y[2], 2)) + ")", xy=(x[2], y[2]), fontsize=10, xycoords='data')# 或者
43plt.annotate("({0},{1})".format(round(x[2],2), round(y[2],2)), xy=(x[2], y[2]), fontsize=10, xycoords='data')
44# xycoords='data' 以data值为基准
45# 设置字体⼤⼩为 10
46# 12. 在图中某些位置显⽰⽂本:text
<(round(x[6],2), round(y[6],2), "good point", fontdict={'size': 10, 'color': 'red'})  # fontdict设置⽂本字体
48# Add text to the axes.
49# 13. 设置显⽰中⽂
52# 14. 设置legend,【注意,'绘图测试’:⼀定要是可迭代格式,例如元组或者列表,要不然只会显⽰
第⼀个字符,也就是legend会显⽰不全】53plt.legend(['绘图测试'], loc=2, fontsize=10)
54# plt.legend(['绘图测试'], loc='upper left', markerscale = 0.5, fontsize = 10) #这个也可
55# markerscale:The relative size of legend markers compared with the originally drawn ones.
56# 15. 保存图⽚ savefig
python安装教程非常详细57plt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)
58# dpi: The resolution in dots per inch,设置分辨率,⽤于改变清晰度
59# If *True*, the axes patches will all be transparent
60# 16. 显⽰图⽚ show
61plt.show()
scatter主要参数:
1def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
2                vmin=None, vmax=None, alpha=None, linewidths=None,
3                verts=None, edgecolors=None,
4                **kwargs):
5        """
6          A scatter plot of *y* vs *x* with varying marker size and/or color.
7
8        Parameters
9        ----------
10        x, y : array_like, shape (n, )
11            The data positions.
12
13        s : scalar or array_like, shape (n, ), optional
14            The marker size in points**2.
15            Default is ``rcParams['lines.markersize'] ** 2``.
16
17          c : color, sequence, or sequence of color, optional, default: 'b'
18            The marker color. Possible values:
19
20            - A single color format string.
21            - A sequence of color specifications of length n.
22            - A sequence of n numbers to be mapped to colors using *cmap* and
23              *norm*.
24            - A 2-D array in which the rows are RGB or RGBA.
25
26            Note that *c* should not be a single numeric RGB or RGBA sequence
27            because that is indistinguishable from an array of values to be
28            colormapped. If you want to specify the same RGB or RGBA value for
29            all points, use a 2-D array with a single row.
30
31        marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
32            The marker style. *marker* can be either an instance of the class
33            or the text shorthand for a particular marker.
34            See `~matplotlib.markers` for more information marker styles.
35
36        cmap : `~lors.Colormap`, optional, default: None
37              A `.Colormap` instance or registered colormap name. *cmap* is only
38            used if *c* is an array of floats. If ``None``, defaults to rc
39            ``ap``.
40        alpha : scalar, optional, default: None
41            The alpha blending value, between 0 (transparent) and 1 (opaque).
42
43        linewidths : scalar or array_like, optional, default: None
44            The linewidth of the marker edges. Note: The default *edgecolors*
45            is 'face'. You may want to change this as well.
46            If *None*, defaults to rcParams ``lines.linewidth``.
14. 设置legend,【注意,'绘图测试’:⼀定要是可迭代格式,例如元组或者列表,要不然只会显⽰第⼀个字符,也就是legend会显⽰不全】
1plt.legend(['绘图测试'], loc=2, fontsize = 10)
2# plt.legend(['绘图测试'], loc='upper left', markerscale = 0.5, fontsize = 10) #这个也可
3#  markerscale:The relative size of legend markers compared with the originally drawn ones.
其参数loc对应为:
运⾏结果: