首頁 > 軟體

Python繪製散點圖的教學詳解

2022-03-16 19:00:48

少廢話,直接上程式碼 

import matplotlib.pyplot as plt
import numpy as np
# 1. 首先是匯入包,建立資料
n = 10
x = np.random.rand(n) * 2# 隨機產生10個0~2之間的x座標
y = np.random.rand(n) * 2# 隨機產生10個0~2之間的y座標
# 2.建立一張figure
fig = plt.figure(1)
# 3. 設定顏色 color 值【可選引數,即可填可不填】,方式有幾種
# colors = np.random.rand(n) # 隨機產生10個0~1之間的顏色值,或者
colors = ['r', 'g', 'y', 'b', 'r', 'c', 'g', 'b', 'k', 'm']  # 可設定亂數取
# 4. 設定點的面積大小 area 值 【可選引數】
area = 20*np.arange(1, n+1)
# 5. 設定點的邊界線寬度 【可選引數】
widths = np.arange(n)# 0-9的數位
# 6. 正式繪製散點圖:scatter
plt.scatter(x, y, s=area, c=colors, linewidths=widths, alpha=0.5, marker='o')
# 7. 設定軸標籤:xlabel、ylabel
#設定X軸標籤
plt.xlabel('X座標')
#設定Y軸標籤
plt.ylabel('Y座標')
# 8. 設定圖示題:title
plt.title('test繪圖函數')
# 9. 設定軸的上下限顯示值:xlim、ylim
# 設定橫軸的上下限值
plt.xlim(-0.5, 2.5)
# 設定縱軸的上下限值
plt.ylim(-0.5, 2.5)
# 10. 設定軸的刻度值:xticks、yticks
# 設定橫軸精準刻度
plt.xticks(np.arange(np.min(x)-0.2, np.max(x)+0.2, step=0.3))
# 設定縱軸精準刻度
plt.yticks(np.arange(np.min(y)-0.2, np.max(y)+0.2, step=0.3))
# 也可按照xlim和ylim來設定
# 設定橫軸精準刻度
plt.xticks(np.arange(-0.5, 2.5, step=0.5))
# 設定縱軸精準刻度
plt.yticks(np.arange(-0.5, 2.5, step=0.5))
 
# 11. 在圖中某些點上(位置)顯示標籤:annotate
# plt.annotate("(" + str(round(x[2], 2)) + ", " + str(round(y[2], 2)) + ")", xy=(x[2], y[2]), fontsize=10, xycoords='data')# 或者
plt.annotate("({0},{1})".format(round(x[2],2), round(y[2],2)), xy=(x[2], y[2]), fontsize=10, xycoords='data')
# xycoords='data' 以data值為基準
# 設定字型大小為 10
# 12. 在圖中某些位置顯示文字:text
plt.text(round(x[6],2), round(y[6],2), "good point", fontdict={'size': 10, 'color': 'red'})  # fontdict設定文字字型
# Add text to the axes.
# 13. 設定顯示中文
plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號
# 14. 設定legend,【注意,'繪圖測試':一定要是可迭代格式,例如元組或者列表,要不然只會顯示第一個字元,也就是legend會顯示不全】
plt.legend(['繪圖測試'], loc=2, fontsize=10)
# plt.legend(['繪圖測試'], loc='upper left', markerscale = 0.5, fontsize = 10) #這個也可
# markerscale:The relative size of legend markers compared with the originally drawn ones.
# 15. 儲存圖片 savefig
plt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)
# dpi: The resolution in dots per inch,設定解析度,用於改變清晰度
# If *True*, the axes patches will all be transparent
# 16. 顯示圖片 show
plt.show()

scatter主要引數:

def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
                vmin=None, vmax=None, alpha=None, linewidths=None,
                verts=None, edgecolors=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``.
        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``.

設定legend,【注意,'繪圖測試’:一定要是可迭代格式,例如元組或者列表,要不然只會顯示第一個字元,也就是legend會顯示不全】

plt.legend(['繪圖測試'], loc=2, fontsize = 10)
# plt.legend(['繪圖測試'], loc='upper left', markerscale = 0.5, fontsize = 10) #這個也可
#  markerscale:The relative size of legend markers compared with the originally drawn ones.

其引數loc對應為:

執行結果:

補充

除了二維的散點圖,Python還能繪製三維的散點圖,下面的範例程式碼

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
 
# 隨機種子
np.random.seed(1)
 
 
def randrange(n, vmin, vmax):
    '''
    使資料分佈均勻(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin
 
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')  # 可進行多圖繪製
 
n = 500
 
# 對於每一組樣式和範圍設定,在由x在[23,32]、y在[0,100]、
# z在[zlow,zhigh]中定義的框中繪製n個隨機點
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)  # 繪圖
 
# X、Y、Z的標籤
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
 
plt.show()

輸出結果:

到此這篇關於Python繪製散點圖的教學詳解的文章就介紹到這了,更多相關Python散點圖內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com