日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python画相关性可视化图上三角_完成这50个Matplotlib代码,你也能画出优秀的图表...

發布時間:2025/4/5 python 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python画相关性可视化图上三角_完成这50个Matplotlib代码,你也能画出优秀的图表... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Matplotlib 是 Python 的繪圖庫。它可與 NumPy 一起使用,提供了一種有效的 MatLab 開源替代方案,也可以和圖形工具包一起使用。和?Pandas、Numpy?并成為數據分析三兄弟(我自封的:)。

雖然比起很多其他圖形庫(Seaborn | pyecharts | plotly | bokeh | pandas_profiling)這個庫丑丑呆呆的,甚至有點難用,但人家畢竟是開山始祖,方法全,能夠支持你各類騷操作的需求。可以說是現在python數據分析中,用的人最多的圖形庫了。

很多同學學習了 matplotlib 之后苦于找不到循序漸進的練習。今天我們這里就給大家一次性整理了 50 個常用的代碼片段!涵蓋了從入門到進階的多種用法。想做可視化的同學不妨收藏起來,慢慢練習。

一、導入

1.導入matplotlib庫簡寫為pltimport matplotlib.pyplot as plt

二、基本圖表

2.用plot方法畫出x=(0,10)間sin的圖像x = np.linspace(0, 10, 30)

plt.plot(x, np.sin(x));

3.用點加線的方式畫出x=(0,10)間sin的圖像plt.plot(x, np.sin(x), '-o');

4.用scatter方法畫出x=(0,10)間sin的點圖像plt.scatter(x, np.sin(x));

5.用餅圖的面積及顏色展示一組4維數據rng = np.random.RandomState(0)

x = rng.randn(100)

y = rng.randn(100)

colors = rng.rand(100)

sizes = 1000 * rng.rand(100)

plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,

cmap='viridis')

plt.colorbar(); # 展示色階

6.繪制一組誤差為±0.8的數據的誤差條圖x = np.linspace(0, 10, 50)

dy = 0.8

y = np.sin(x) + dy * np.random.randn(50)

plt.errorbar(x, y, yerr=dy, fmt='.k')

7.繪制一個柱狀圖x = [1,2,3,4,5,6,7,8]

y = [3,1,4,5,8,9,7,2]

label=['A','B','C','D','E','F','G','H']

plt.bar(x,y,tick_label = label);

8.繪制一個水平方向柱狀圖plt.barh(x,y,tick_label = label);

9.繪制1000個隨機值的直方圖data = np.random.randn(1000)

plt.hist(data);

10.設置直方圖分30個bins,并設置為頻率分布plt.hist(data, bins=30,histtype='stepfilled', density=True)

plt.show();

11.在一張圖中繪制3組不同的直方圖,并設置透明度x1 = np.random.normal(0, 0.8, 1000)

x2 = np.random.normal(-2, 1, 1000)

x3 = np.random.normal(3, 2, 1000)

kwargs = dict(alpha=0.3, bins=40, density = True)

plt.hist(x1, **kwargs);

plt.hist(x2, **kwargs);

plt.hist(x3, **kwargs);

12.繪制一張二維直方圖mean = [0, 0]

cov = [[1, 1], [1, 2]]

x, y = np.random.multivariate_normal(mean, cov, 10000).T

plt.hist2d(x, y, bins=30);

13.繪制一張設置網格大小為30的六角形直方圖plt.hexbin(x, y, gridsize=30);

三、自定義圖表元素

14.繪制x=(0,10)間sin的圖像,設置線性為虛線x = np.linspace(0,10,100)

plt.plot(x,np.sin(x),'--');

15設置y軸顯示范圍為(-1.5,1.5)x = np.linspace(0,10,100)

plt.plot(x, np.sin(x))

plt.ylim(-1.5, 1.5);

16.設置x,y軸標簽variable x,value yx = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y, label='sin(x)')

plt.xlabel('variable x');

plt.ylabel('value y');

17.設置圖表標題“三角函數”x = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y, label='sin(x)')

plt.title('三角函數');

18.顯示網格x = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y)

plt.grid()

19.繪制平行于x軸y=0.8的水平參考線x = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y)

plt.axhline(y=0.8, ls='--', c='r')

20.繪制垂直于x軸x<4 and x>6的參考區域,以及y軸y<0.2 and y>-0.2的參考區域x = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y)

plt.axvspan(xmin=4, xmax=6, facecolor='r', alpha=0.3) # 垂直x軸

plt.axhspan(ymin=-0.2, ymax=0.2, facecolor='y', alpha=0.3); ?# 垂直y軸

21.添加注釋文字sin(x)x = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y)

plt.text(3.2, 0, 'sin(x)', weight='bold', color='r');

22.用箭頭標出第一個峰值x = np.linspace(0.05, 10, 100)

y = np.sin(x)

plt.plot(x, y)

plt.annotate('maximum',xy=(np.pi/2, 1),xytext=(np.pi/2+1, 1),

weight='bold',

color='r',

arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'));

四、自定義圖例

23.在一張圖里繪制sin,cos的圖形,并展示圖例x = np.linspace(0, 10, 1000)

fig, ax = plt.subplots()

ax.plot(x, np.sin(x), label='sin')

ax.plot(x, np.cos(x), '--', label='cos')

ax.legend();

24.調整圖例在左上角展示,且不顯示邊框ax.legend(loc='upper left', frameon=False);

fig

25.調整圖例在畫面下方居中展示,且分成2列ax.legend(frameon=False, loc='lower center', ncol=2)

fig

26.繪制的圖像,并只顯示前2者的圖例y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))

lines = plt.plot(x, y)

# lines 是 plt.Line2D 類型的實例的列表

plt.legend(lines[:2], ['first', 'second']);

# 第二個方法

#plt.plot(x, y[:, 0], label='first')

#plt.plot(x, y[:, 1], label='second')

#plt.plot(x, y[:, 2:])

#plt.legend(framealpha=1, frameon=True);

27.將圖例分不同的區域展示fig, ax = plt.subplots()

lines = []

styles = ['-', '--', '-.', ':']

x = np.linspace(0, 10, 1000)

for i in range(4):

lines += ax.plot(x, np.sin(x - i * np.pi / 2),styles[i], color='black')

ax.axis('equal')

# 設置第一組標簽

ax.legend(lines[:2], ['line A', 'line B'],

loc='upper right', frameon=False)

# 創建第二組標簽

from matplotlib.legend import Legend

leg = Legend(ax, lines[2:], ['line C', 'line D'],

loc='lower right', frameon=False)

ax.add_artist(leg);

五、自定義色階

28.展示色階x = np.linspace(0, 10, 1000)

I = np.sin(x) * np.cos(x[:, np.newaxis])

plt.imshow(I)

plt.colorbar();

29.改變配色為'gray'plt.imshow(I, cmap='gray');

30.將色階分成6個離散值顯示plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))

plt.colorbar()

plt.clim(-1, 1);

六、多子圖

31.在一個1010的畫布中,(0.65,0.65)的位置創建一個0.20.2的子圖ax1 = plt.axes()

ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])

32.在2個子圖中,顯示sin(x)和cos(x)的圖像fig = plt.figure()

ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-1.2, 1.2))

ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))

x = np.linspace(0, 10)

ax1.plot(np.sin(x));

ax2.plot(np.cos(x));

33.用for創建6個子圖,并且在圖中標識出對應的子圖坐標for i in range(1, 7):

plt.subplot(2, 3, i)

plt.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')

# 方法二

# fig = plt.figure()

# fig.subplots_adjust(hspace=0.4, wspace=0.4)

# for i in range(1, 7):

# ? ? ax = fig.add_subplot(2, 3, i)

# ? ? ax.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')

34.設置相同行和列共享x,y軸fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')

35.用[]的方式取出每個子圖,并添加子圖座標文字for i in range(2):

for j in range(3):

ax[i, j].text(0.5, 0.5, str((i, j)),fontsize=18, ha='center')

fig

36.組合繪制大小不同的子圖,樣式如下

Image Namegrid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)

plt.subplot(grid[0, 0])

plt.subplot(grid[0, 1:])

plt.subplot(grid[1, :2])

plt.subplot(grid[1, 2]);

37.顯示一組二維數據的頻度分布,并分別在x,y軸上,顯示該維度的數據的頻度分布mean = [0, 0]

cov = [[1, 1], [1, 2]]

x, y = np.random.multivariate_normal(mean, cov, 3000).T

# Set up the axes with gridspec

fig = plt.figure(figsize=(6, 6))

grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)

main_ax = fig.add_subplot(grid[:-1, 1:])

y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)

x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)

# scatter points on the main axes

main_ax.scatter(x, y,s=3,alpha=0.2)

# histogram on the attached axes

x_hist.hist(x, 40, histtype='stepfilled',

orientation='vertical')

x_hist.invert_yaxis()

y_hist.hist(y, 40, histtype='stepfilled',

orientation='horizontal')

y_hist.invert_xaxis()

七、三維圖像

38.創建一個三維畫布from mpl_toolkits import mplot3d

fig = plt.figure()

ax = plt.axes(projection='3d')

39.繪制一個三維螺旋線ax = plt.axes(projection='3d')

# Data for a three-dimensional line

zline = np.linspace(0, 15, 1000)

xline = np.sin(zline)

yline = np.cos(zline)

ax.plot3D(xline, yline, zline);

40.繪制一組三維點ax = plt.axes(projection='3d')

zdata = 15 * np.random.random(100)

xdata = np.sin(zdata) + 0.1 * np.random.randn(100)

ydata = np.cos(zdata) + 0.1 * np.random.randn(100)

ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');

八、寶可夢數據集可視化

41.展示前5個寶可夢的Defense,Attack,HP的堆積條形圖pokemon = df['Name'][:5]

hp = df['HP'][:5]

attack = df['Attack'][:5]

defense = df['Defense'][:5]

ind = [x for x, _ in enumerate(pokemon)]

plt.figure(figsize=(10,10))

plt.bar(ind, defense, width=0.8, label='Defense', color='blue', bottom=attack+hp)

plt.bar(ind, attack, width=0.8, label='Attack', color='gold', bottom=hp)

plt.bar(ind, hp, width=0.8, label='Hp', color='red')

plt.xticks(ind, pokemon)

plt.ylabel("Value")

plt.xlabel("Pokemon")

plt.legend(loc="upper right")

plt.title("5 Pokemon Defense & Attack & Hp")

plt.show()

42.展示前5個寶可夢的Attack,HP的簇狀條形圖N = 5

pokemon_hp = df['HP'][:5]

pokemon_attack = df['Attack'][:5]

ind = np.arange(N)

width = 0.35

plt.bar(ind, pokemon_hp, width, label='HP')

plt.bar(ind + width, pokemon_attack, width,label='Attack')

plt.ylabel('Values')

plt.title('Pokemon Hp & Attack')

plt.xticks(ind + width / 2, (df['Name'][:5]),rotation=45)

plt.legend(loc='best')

plt.show()

43.展示前5個寶可夢的Defense,Attack,HP的堆積圖x = df['Name'][:4]

y1 = df['HP'][:4]

y2 = df['Attack'][:4]

y3 = df['Defense'][:4]

labels = ["HP ", "Attack", "Defense"]

fig, ax = plt.subplots()

ax.stackplot(x, y1, y2, y3)

ax.legend(loc='upper left', labels=labels)

plt.xticks(rotation=90)

plt.show()

44.公用x軸,展示前5個寶可夢的Defense,Attack,HP的折線圖x = df['Name'][:5]

y1 = df['HP'][:5]

y2 = df['Attack'][:5]

y3 = df['Defense'][:5]

# Create two subplots sharing y axis

fig, (ax1, ax2,ax3) = plt.subplots(3, sharey=True)

ax1.plot(x, y1, 'ko-')

ax1.set(title='3 subplots', ylabel='HP')

ax2.plot(x, y2, 'r.-')

ax2.set(xlabel='Pokemon', ylabel='Attack')

ax3.plot(x, y3, ':')

ax3.set(xlabel='Pokemon', ylabel='Defense')

plt.show()

45.展示前15個寶可夢的Attack,HP的折線圖plt.plot(df['HP'][:15], '-r',label='HP')

plt.plot(df['Attack'][:15], ':g',label='Attack')

plt.legend();

46.用scatter的x,y,c屬性,展示所有寶可夢的Defense,Attack,HP數據x = df['Attack']

y = df['Defense']

colors = df['HP']

plt.scatter(x, y, c=colors, alpha=0.5)

plt.title('Scatter plot')

plt.xlabel('HP')

plt.ylabel('Attack')

plt.colorbar();

47.展示所有寶可夢的***力的分布直方圖,bins=10x = df['Attack']

num_bins = 10

n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)

plt.title('Histogram')

plt.xlabel('Attack')

plt.ylabel('Value')

plt.show()

48.展示所有寶可夢Type 1的餅圖plt.figure(1, figsize=(8,8))

df['Type 1'].value_counts().plot.pie(autopct="%1.1f%%")

plt.legend()

49.展示所有寶可夢Type 1的柱狀圖ax = df['Type 1'].value_counts().plot.bar(figsize = (12,6),fontsize = 14)

ax.set_title("Pokemon Type 1 Count", fontsize = 20)

ax.set_xlabel("Pokemon Type 1", fontsize = 20)

ax.set_ylabel("Value", fontsize = 20)

plt.show()

50.展示綜合評分最高的10只寶可夢的系數間的相關系數矩陣import seaborn as sns

top_10_pokemon=df.sort_values(by='Total',ascending=False).head(10)

corr=top_10_pokemon.corr()

fig, ax=plt.subplots(figsize=(10, 6))

sns.heatmap(corr,annot=True)

ax.set_ylim(9, 0)

plt.show()

作者:王大毛

來源:Python大數據分析

總結

以上是生活随笔為你收集整理的python画相关性可视化图上三角_完成这50个Matplotlib代码,你也能画出优秀的图表...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。