python數(shù)據(jù)處理4

#==============================================================================

#==============================================================================

# 第4章 學(xué)習(xí)更多圖表和定制化 99

# 4.1 簡(jiǎn)介 99

#==============================================================================

#==============================================================================

# 4.2 設(shè)置坐標(biāo)軸標(biāo)簽的透明度和大小 100

#==============================================================================

4.2.1 準(zhǔn)備工作 100

4.2.2 操作步驟 100

4.2.3 工作原理 101

4.2.4 補(bǔ)充說(shuō)明 102

import matplotlib.pyplot as plt

from matplotlib import patheffects

import numpy as np

data = np.random.randn(70)

fontsize = 18

plt.plot(data)

title = "This is figure title";

x_label = "This is x axis label";y_label = "This is y axis label"

title_text_obj = plt.title(title, fontsize=fontsize, verticalalignment='bottom')

title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()])

'''customize shadow properties

offset_xy -- set the 'angle' of the shadow

shadow_rgbFace -- set the color of the shadow

patch_alpha -- setup the transparaency of the shadow

亦可繼承patheffects._Base類,并重寫(xiě)draw_path方法

'''

pe = patheffects.withSimplePatchShadow(

? ? ? ? offset_xy = (1, -1),

? ? ? ? shadow_rgbFace = (1.0,0.0,0.0),

? ? ? ? patch_alpha =? 0.8)

# apply them to the xaxis and yaxis labels

xlabel_obj = plt.xlabel(x_label, fontsize=fontsize, alpha=0.5)

xlabel_obj.set_path_effects([pe])

ylabel_obj = plt.ylabel(y_label, fontsize=fontsize, alpha=0.5)

ylabel_obj.set_path_effects([pe])

plt.show()

#==============================================================================

# 4.3 為圖表線條添加陰影 102

#==============================================================================

4.3.1 準(zhǔn)備工作 103

4.3.2 操作步驟 103

4.3.3 工作原理 105

4.3.4 補(bǔ)充說(shuō)明 105

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.transforms as transforms

def setup(layout=None):

? ? assert layout is not None

? ? fig = plt.figure()

? ? ax = fig.add_subplot(layout)

? ? return fig, ax

def get_signal():

? ? t = np.arange(0., 2.5, 0.01)

? ? s = np.sin(5 * np.pi * t)

? ? return t, s?

def plot_signal(t, s):

? ? line, = axes.plot(t, s, linewidth=5, color='magenta')

? ? return line,

def make_shadow(fig, axes, line, t, s):

? ? delta = 2 / 72.? # how many points to move the shadow

? ? offset = transforms.ScaledTranslation(delta, -delta, fig.dpi_scale_trans)

? ? offset_transform = axes.transData + offset

? ? # We plot the same data, but now using offset transform

? ? # zorder -- to render it below the line

? ? axes.plot(t, s, linewidth=5, color='gray',

? ? ? ? ? ? ? transform=offset_transform,

? ? ? ? ? ? ? zorder=0.5 * line.get_zorder())

if __name__ == "__main__":

? ? fig,axes = setup(111)

? ? t, s = get_signal()

? ? line, = plot_signal(t, s)

? ? make_shadow(fig, axes, line, t, s)

? ? axes.set_title('Shadow effect using an offset transform')

? ? plt.show()

#==============================================================================

# 4.4 向圖表添加數(shù)據(jù)表 106

#==============================================================================

4.4.1 準(zhǔn)備工作 106

4.4.2 操作步驟 106

4.4.3 工作原理 107

4.4.4 補(bǔ)充說(shuō)明 107

import matplotlib.pylab as plt

import numpy as np

plt.figure()

axes=plt.gca()

y= np.random.randn(9)

col_labels=['col1','col2','col3']

row_labels=['row1','row2','row3']

table_vals=[[11,12,13],[21,22,23],[28,29,30]]

row_colors=['red','gold','green']

'''基本的函數(shù)簽名

table(? cellText=None, cellColours=None,

? ? ? ? colWidths = None,

? ? ? ? rowLabels=None, rowColours=None, rowLoc='left'

? ? ? ? colLabels=None, colColours=None, rowLoc='left'

? ? ? ? loc='upper right', bbox=None)

'''

the_table = plt.table(cellText=table_vals,

? ? ? ? ? ? ? ? ? colWidths = [0.1]*3,

? ? ? ? ? ? ? ? ? rowLabels=row_labels,

? ? ? ? ? ? ? ? ? colLabels=col_labels,

? ? ? ? ? ? ? ? ? rowColours=row_colors,

? ? ? ? ? ? ? ? ? loc='upper right')

plt.text(12,3.4,'Table Title',size=8)

plt.plot(y)

plt.show()

#==============================================================================

# 4.5 使用subplots(子區(qū)) 108

#==============================================================================

4.5.1 準(zhǔn)備工作 108

4.5.2 操作步驟 108

4.5.3 工作原理 110

4.5.4 補(bǔ)充說(shuō)明 110

import matplotlib.pyplot as plt

plt.figure(0)

'''

? ? fig,ax = plt.subplots 創(chuàng)建普通布局的子區(qū)

? ? plt.subplots_adjust調(diào)整子區(qū)的布局

'''

axes1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)

axes2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)

axes3 = plt.subplot2grid((3, 3), (1, 2))

axes4 = plt.subplot2grid((3, 3), (2, 0))

axes5 = plt.subplot2grid((3, 3), (2, 1), colspan=2)

# tidy up tick labels size

all_axes = plt.gcf().axes

for ax in all_axes:

? ? for ticklabel in ax.get_xticklabels() + ax.get_yticklabels():

? ? ? ? ticklabel.set_fontsize(10)

plt.suptitle("Demo of subplot2grid")

plt.show()

#==============================================================================

# 4.6 定制化網(wǎng)格 110

#==============================================================================

4.6.1準(zhǔn)備工作 110

4.6.2 操作步驟 112

4.6.3 工作原理 114

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import ImageGrid

from matplotlib.cbook import get_sample_data

def get_grid(fig=None, layout=None, nrows_ncols=None):

? ? assert fig is not None;assert layout is not None;assert nrows_ncols is not None

? ? grid = ImageGrid(fig, layout, nrows_ncols=nrows_ncols, axes_pad=0.05, add_all=True, label_mode="L")

? ? return grid

def load_images_to_grid(grid, Z, *images):

? ? min,max = Z.min(),Z.max()

? ? for i, image in enumerate(images):

? ? ? ? axes = grid[i]

? ? ? ? axes.imshow(image, origin="lower", vmin=min, vmax=max,interpolation="nearest")

if __name__ == "__main__":

? ? fig = plt.figure(1, (8, 6)) ;? ? grid = get_grid(fig, 111, (1, 3))

? ? # z is a numpy array of 15x15

? ? Z = np.load(get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False))

? ? # Slice image

? ? image1 = Z ;? ? image2 = Z[:, :10];? ? image3 = Z[:, 10:]

? ? load_images_to_grid(grid, Z, image1, image2, image3)

? ? plt.draw()

? ? plt.show()

#==============================================================================

# 4.7 創(chuàng)建等高線圖 114

#==============================================================================

4.7.1 準(zhǔn)備工作 114

4.7.2 操作步驟 115

4.7.3 工作原理 117

import numpy as np

import matplotlib as mpl

import matplotlib.pyplot as plt

'''

等高線顯示的是矩陣的等值線isolines

等值線是用數(shù)值相等的各點(diǎn)連成的曲線

'''

x = np.arange(-1.5, 1.5, 0.1)

y = np.arange(-1.5, 1.5, 0.1)

X, Y = np.meshgrid(x, y)# Make grids of points

Z = (1 - (X ** 2 + Y ** 2)) * np.exp(-Y ** 3 / 3)

N = np.arange(-1, 1, 0.5)# Number of isolines

'''

? ? contour()

? ? contour(Z)? 繪制Z數(shù)組的等高線,自動(dòng)選擇水平值

? ? contour(Z,N) 水平數(shù)由N指定,自動(dòng)選擇水平值

? ? contour(Z,V) 繪制Z數(shù)組的等高線,水平值在V中指定


? ? contour(X,Y,Z) 繪制X、Y和Z的等高線.X和Y數(shù)組為(x,y)平面坐標(biāo)(surface coordinates)

? ? contour(X,Y,Z,N)

'''

CS = plt.contour(Z, N, linewidths=2, cmap=mpl.cm.jet)

plt.clabel(CS, inline=True, fmt='%1.1f', fontsize=10)

plt.colorbar(CS)

plt.title('My function: $z=(1-x^2+y^2) e^{-(y^3)/3}$')

plt.show()

#==============================================================================

# 4.8 填充圖表底層區(qū)域 117

#==============================================================================

4.8.1 準(zhǔn)備工作 118

4.8.2 操作步驟 118

4.8.3 工作原理 120

import matplotlib.pyplot as plt

import numpy as np

from math import sqrt

t =range(1000)

y = [sqrt(i) for i in t]

plt.plot(t,y,color='red',lw=2)

plt.fill_between(t,y,color='silver')

plt.show()

----------------------------------------------

import matplotlib.pyplot as plt

import numpy as np

from math import sqrt

x = np.arange(0.0, 2, 0.01)

y1 = np.sin(np.pi*x)

y2 = 1.7*np.sin(4*np.pi*x)

fig = plt.figure()

axes1 = fig.add_subplot(211)

axes1.plot(x, y1, x, y2, color='grey')

axes1.fill_between(x, y1, y2, where=y2<=y1, facecolor='blue', interpolate=True)

axes1.fill_between(x, y1, y2, where=y2>=y1, facecolor='gold', interpolate=True)

axes1.set_title('Blue where y2 <= y1. Gold-color where y2 >= y1.')

axes1.set_ylim(-2,2)

#屏蔽數(shù)組中給定值的所有值

y2 = np.ma.masked_greater(y2, 1.0)

axes2 = fig.add_subplot(212, sharex=axes1)

axes2.plot(x, y1, x, y2, color='black')

axes2.fill_between(x, y1, y2, where=y2<=y1, facecolor='blue', interpolate=True)

axes2.fill_between(x, y1, y2, where=y2>=y1, facecolor='gold', interpolate=True)

axes2.set_title('Same as above, but mask')

axes2.set_ylim(-2,2)

axes2.grid('on')

plt.show()

#==============================================================================

# 4.9 繪制極線圖 121

#==============================================================================

4.9.1 準(zhǔn)備工作 121

4.9.2 操作步驟 121

4.9.3 工作原理 123

import numpy as np

import matplotlib.cm as cm

import matplotlib.pyplot as plt

figsize = 7; N = 18

colormap = lambda r: cm.Set2(r / 20.)

# number of bars

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

ax = fig.add_axes([0.2, 0.2, 0.7, 0.7], polar=True)

theta = np.arange(0.0, 2 * np.pi, 2 * np.pi/N)#角度theta集合

radii = 20 * np.random.rand(N)? ? ? ? ? #極線距離

width = np.pi / 4 * np.random.rand(N)? #每個(gè)極線條的寬度集合

bars = ax.bar(theta, radii, width=width, bottom=0.0)

for r, bar in zip(radii, bars):

? ? bar.set_facecolor(colormap(r))

? ? bar.set_alpha(0.6)

plt.show()

#==============================================================================

# 4.10 使用極線條可視化文件系統(tǒng)樹(shù) 123

#==============================================================================

4.10.1 準(zhǔn)備工作 123

4.10.2 操作步驟 123

4.10.3 工作原理 126

import os

import sys

import matplotlib.pyplot as plt

import matplotlib.cm as cm

import numpy as np

def build_folders(start_path):

? ? folders = []

? ? for each in get_directories(start_path):

? ? ? ? size = get_size(each)

? ? ? ? if size >= 25 * 1024 * 1024:

? ? ? ? ? ? folders.append({'size': size, 'path': each})

? ? for each in folders:

? ? ? ? print "Path: " + os.path.basename(each['path'])

? ? ? ? print "Size: " + str(each['size'] / 1024 / 1024) + " MB"

? ? return folders

def get_size(path):

? ? assert path is not None

? ? total_size = 0

? ? for dirpath, dirnames, filenames in os.walk(path):

? ? ? ? for f in filenames:

? ? ? ? ? ? fp = os.path.join(dirpath, f)

? ? ? ? ? ? try:

? ? ? ? ? ? ? ? size = os.path.getsize(fp)

? ? ? ? ? ? ? ? total_size += size

? ? ? ? ? ? ? ? #print "Size of '{0}' is {1}".format(fp, size)

? ? ? ? ? ? except OSError as err:

? ? ? ? ? ? ? ? print str(err)

? ? ? ? ? ? ? ? pass

? ? return total_size

def get_directories(path):

? ? dirs = set()

? ? for dirpath, dirnames, filenames in os.walk(path):

? ? ? ? dirs = set([os.path.join(dirpath, x) for x in dirnames])

? ? ? ? break? # we just want the first one

? ? return dirs

def draw(folders):

? ? """ Draw folder size for given folder"""

? ? figsize = (8, 8)? # keep the figure square

? ? ldo, rup = 0.1, 0.8? # left down, right up coordinates, normalized

? ? fig = plt.figure(figsize=figsize)

? ? ax = fig.add_axes([ldo, ldo, rup, rup], polar=True)

? ? # transform data

? ? x = [os.path.basename(x['path']) for x in folders]

? ? y = [y['size'] / 1024 / 1024 for y in folders]

? ? theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / len(x))

? ? radii = y

? ? bars = ax.bar(theta, radii)

? ? middle = 90 / len(x)

? ? theta_ticks = [t * (180 / np.pi) + middle for t in theta]

? ? lines, labels = plt.thetagrids(theta_ticks, labels=x, frac=0.5)

? ? for step, each in enumerate(labels):

? ? ? ? each.set_rotation(theta[step] * (180 / np.pi) + middle)

? ? ? ? each.set_fontsize(8)

? ? # configure bars

? ? colormap = lambda r: cm.Set2(r / len(x))

? ? for r, each in zip(radii, bars):

? ? ? ? each.set_facecolor(colormap(r))

? ? ? ? each.set_alpha(0.5)

? ? plt.show()

if __name__ == '__main__':

? ? if len(sys.argv) is not 2:

? ? ? ? print "ERROR: Please supply path to folder."

? ? ? ? sys.exit(-1)

? ? start_path = sys.argv[1]

? ? if not os.path.exists(start_path):

? ? ? ? print "ERROR: Path must exits."

? ? ? ? sys.exit(-1)

? ? folders = build_folders(start_path)

? ? if len(folders) < 1:

? ? ? ? print "ERROR: Path does not contain any folders."

? ? ? ? sys.exit(-1)

? ? draw(folders)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蘸炸,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子豫尽,更是在濱河造成了極大的恐慌槐瑞,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異唧喉,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)忍抽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門八孝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人鸠项,你說(shuō)我怎么就攤上這事干跛。” “怎么了祟绊?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵楼入,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我牧抽,道長(zhǎng)嘉熊,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任扬舒,我火速辦了婚禮阐肤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘呼巴。我一直安慰自己泽腮,他們只是感情好御蒲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著诊赊,像睡著了一般厚满。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上碧磅,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天碘箍,我揣著相機(jī)與錄音,去河邊找鬼鲸郊。 笑死丰榴,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的秆撮。 我是一名探鬼主播四濒,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼职辨!你這毒婦竟也來(lái)了盗蟆?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤舒裤,失蹤者是張志新(化名)和其女友劉穎喳资,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體腾供,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡仆邓,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了伴鳖。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片节值。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖黎侈,靈堂內(nèi)的尸體忽然破棺而出察署,到底是詐尸還是另有隱情,我是刑警寧澤峻汉,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布贴汪,位于F島的核電站,受9級(jí)特大地震影響休吠,放射性物質(zhì)發(fā)生泄漏扳埂。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一瘤礁、第九天 我趴在偏房一處隱蔽的房頂上張望阳懂。 院中可真熱鬧,春花似錦、人聲如沸岩调。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)号枕。三九已至缰揪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間葱淳,已是汗流浹背钝腺。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留赞厕,地道東北人艳狐。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像皿桑,于是被迫代替她去往敵國(guó)和親毫目。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容