#==============================================================================
#==============================================================================
# 第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)