python数据处理4

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

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

# 第4章 学习更多图表和定制化 99

# 4.1 简介 99

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

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

# 4.2 设置坐标轴标签的透明度和大小 100

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

4.2.1 准备工作 100

4.2.2 操作步骤 100

4.2.3 工作原理 101

4.2.4 补充说明 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类,并重写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 准备工作 103

4.3.2 操作步骤 103

4.3.3 工作原理 105

4.3.4 补充说明 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 向图表添加数据表 106

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

4.4.1 准备工作 106

4.4.2 操作步骤 106

4.4.3 工作原理 107

4.4.4 补充说明 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']

'''基本的函数签名

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(子区) 108

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

4.5.1 准备工作 108

4.5.2 操作步骤 108

4.5.3 工作原理 110

4.5.4 补充说明 110

import matplotlib.pyplot as plt

plt.figure(0)

'''

    fig,ax = plt.subplots 创建普通布局的子区

    plt.subplots_adjust调整子区的布局

'''

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 定制化网格 110

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

4.6.1准备工作 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 创建等高线图 114

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

4.7.1 准备工作 114

4.7.2 操作步骤 115

4.7.3 工作原理 117

import numpy as np

import matplotlib as mpl

import matplotlib.pyplot as plt

'''

等高线显示的是矩阵的等值线isolines

等值线是用数值相等的各点连成的曲线

'''

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数组的等高线,自动选择水平值

    contour(Z,N) 水平数由N指定,自动选择水平值

    contour(Z,V) 绘制Z数组的等高线,水平值在V中指定


    contour(X,Y,Z) 绘制X、Y和Z的等高线.X和Y数组为(x,y)平面坐标(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 填充图表底层区域 117

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

4.8.1 准备工作 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)

#屏蔽数组中给定值的所有值

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 准备工作 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)  #每个极线条的宽度集合

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 使用极线条可视化文件系统树 123

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

4.10.1 准备工作 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)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容