50題matplotlib從入門到精通

Matplotlib 是 Python 的繪圖庫(kù)涛漂。 它可與 NumPy 一起使用看蚜,提供了一種有效的 MatLab 開(kāi)源替代方案,也可以和圖形工具包一起使用甩鳄。和Pandas逞度、Numpy并成為數(shù)據(jù)科學(xué)三兄弟(我自己想的)。

點(diǎn)擊此處妙啃,不用搭環(huán)境第晰,直接在線運(yùn)行??

50題matplotlib從入門到精通

本教程部分參考:Matplotlib Tutorial for Beginners寶可夢(mèng)數(shù)據(jù)練手

文中提及數(shù)據(jù)集:寶可夢(mèng)屬性數(shù)據(jù)集

其他x題系列:

一品抽、導(dǎo)入

1.導(dǎo)入matplotlib庫(kù)簡(jiǎn)寫(xiě)為plt

import matplotlib.pyplot as plt

二、基本圖表

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

x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x));

3.用點(diǎn)加線的方式畫(huà)出x=(0,10)間sin的圖像

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

4.用scatter方法畫(huà)出x=(0,10)間sin的點(diǎn)圖像

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

5.用餅圖的面積及顏色展示一組4維數(shù)據(jù)

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的數(shù)據(jù)的誤差條圖

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.繪制一個(gè)柱狀圖

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);

image.png

8.繪制一個(gè)水平方向柱狀圖

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

9.繪制1000個(gè)隨機(jī)值的直方圖

data = np.random.randn(1000)
plt.hist(data);

10.設(shè)置直方圖分30個(gè)bins甜熔,并設(shè)置為頻率分布

plt.hist(data, bins=30,histtype='stepfilled', density=True)
plt.show();

11.在一張圖中繪制3組不同的直方圖圆恤,并設(shè)置透明度


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.繪制一張?jiān)O(shè)置網(wǎng)格大小為30的六角形直方圖

plt.hexbin(x, y, gridsize=30);

三、自定義圖表元素

14.繪制x=(0,10)間sin的圖像腔稀,設(shè)置線性為虛線

x = np.linspace(0,10,100)
plt.plot(x,np.sin(x),'--');

15設(shè)置y軸顯示范圍為(-1.5,1.5)

x = np.linspace(0,10,100)
plt.plot(x, np.sin(x))
plt.ylim(-1.5, 1.5);

16.設(shè)置x,y軸標(biāo)簽variable x盆昙,value y

x = 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.設(shè)置圖表標(biāo)題“三角函數(shù)”

x = np.linspace(0.05, 10, 100)
y = np.sin(x)
plt.plot(x, y, label='sin(x)')
plt.title('三角函數(shù)');

18.顯示網(wǎng)格

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的參考區(qū)域,以及y軸y<0.2 and y>-0.2的參考區(qū)域

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.用箭頭標(biāo)出第一個(gè)峰值

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.調(diào)整圖例在左上角展示,且不顯示邊框

ax.legend(loc='upper left', frameon=False);
fig

25.調(diào)整圖例在畫(huà)面下方居中展示诵闭,且分成2列

ax.legend(frameon=False, loc='lower center', ncol=2)
fig

26.繪制sin(x),sin(x+\pi /2),sin(x+\pi)的圖像炼团,并只顯示前2者的圖例

y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)

# lines 是 plt.Line2D 類型的實(shí)例的列表
plt.legend(lines[:2], ['first', 'second']);

# 第二個(gè)方法
#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.將圖例分不同的區(qū)域展示

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')

# 設(shè)置第一組標(biāo)簽
ax.legend(lines[:2], ['line A', 'line B'],
          loc='upper right', frameon=False)

# 創(chuàng)建第二組標(biāo)簽
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個(gè)離散值顯示

plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
plt.colorbar()
plt.clim(-1, 1);

六疏尿、多子圖

31.在一個(gè)1010的畫(huà)布中瘟芝,(0.65,0.65)的位置創(chuàng)建一個(gè)0.20.2的子圖

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

32.在2個(gè)子圖中,顯示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創(chuàng)建6個(gè)子圖褥琐,并且在圖中標(biāo)識(shí)出對(duì)應(yīng)的子圖坐標(biāo)

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.設(shè)置相同行和列共享x,y軸

fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')

35.用[]的方式取出每個(gè)子圖锌俱,并添加子圖座標(biāo)文字

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
grid = 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.顯示一組二維數(shù)據(jù)的頻度分布敌呈,并分別在x,y軸上贸宏,顯示該維度的數(shù)據(jù)的頻度分布

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.創(chuàng)建一個(gè)三維畫(huà)布

from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection='3d')

39.繪制一個(gè)三維螺旋線

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.繪制一組三維點(diǎn)

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');

八磕洪、寶可夢(mèng)數(shù)據(jù)集可視化

41.展示前5個(gè)寶可夢(mèng)的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個(gè)寶可夢(mèng)的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個(gè)寶可夢(mèng)的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個(gè)寶可夢(mèng)的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個(gè)寶可夢(mèng)的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屬性,展示所有寶可夢(mèng)的Defense,Attack,HP數(shù)據(jù)

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.展示所有寶可夢(mèng)的攻擊力的分布直方圖褐鸥,bins=10

x = 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.展示所有寶可夢(mèng)Type 1的餅圖

plt.figure(1, figsize=(8,8))
df['Type 1'].value_counts().plot.pie(autopct="%1.1f%%")
plt.legend()

49.展示所有寶可夢(mèng)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.展示綜合評(píng)分最高的10只寶可夢(mèng)的系數(shù)間的相關(guān)系數(shù)矩陣

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()

點(diǎn)擊此處,不用搭環(huán)境赐稽,直接在線運(yùn)行??

50題matplotlib從入門到精通

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末叫榕,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子姊舵,更是在濱河造成了極大的恐慌晰绎,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件括丁,死亡現(xiàn)場(chǎng)離奇詭異荞下,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門尖昏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)仰税,“玉大人,你說(shuō)我怎么就攤上這事抽诉≡纱兀” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵迹淌,是天一觀的道長(zhǎng)河绽。 經(jīng)常有香客問(wèn)我,道長(zhǎng)唉窃,這世上最難降的妖魔是什么耙饰? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮纹份,結(jié)果婚禮上苟跪,老公的妹妹穿的比我還像新娘。我一直安慰自己矮嫉,他們只是感情好削咆,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著蠢笋,像睡著了一般拨齐。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上昨寞,一...
    開(kāi)封第一講書(shū)人閱讀 51,708評(píng)論 1 305
  • 那天瞻惋,我揣著相機(jī)與錄音,去河邊找鬼援岩。 笑死歼狼,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的享怀。 我是一名探鬼主播羽峰,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼添瓷!你這毒婦竟也來(lái)了梅屉?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤鳞贷,失蹤者是張志新(化名)和其女友劉穎坯汤,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體搀愧,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡惰聂,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年疆偿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片搓幌。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡杆故,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出鼻种,到底是詐尸還是另有隱情反番,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布叉钥,位于F島的核電站罢缸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏投队。R本人自食惡果不足惜枫疆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望敷鸦。 院中可真熱鬧息楔,春花似錦、人聲如沸扒披。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)碟案。三九已至愿险,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間价说,已是汗流浹背辆亏。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鳖目,地道東北人扮叨。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像领迈,于是被迫代替她去往敵國(guó)和親彻磁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355