2016-08-03 88 views
2

我的情节是像下面蟒蛇matplotlib绘制许多子图使用相同的参数

fig = plt.figure(figsize=(7,3))            
ax1 = fig.add_subplot(1,3,1)             
ax2 = fig.add_subplot(1,3,2)             
ax3 = fig.add_subplot(1,3,3) 
ax1.scatter(x11, y11, s=50, alpha=0.5, c='orange', marker='o') 
ax1.scatter(x12, y12, s=50, alpha=0.5, c='blue', marker='s') 
ax2.scatter(x21, y21, s=50, alpha=0.5, c='orange', marker='o') 
ax2.scatter(x22, y22, s=50, alpha=0.5, c='blue', marker='s') 
ax3.scatter(x31, y31, s=50, alpha=0.5, c='orange', marker='o') 
ax3.scatter(x32, y32, s=50, alpha=0.5, c='blue', marker='s') 

这似乎有点多余一遍一遍设置s=50, alpha=0.5。有没有办法为所有人设置一次?对于颜色和标记,有没有办法将它们写在一个地方,以便更容易修改?

回答

3

你可以这样做:

fig = plt.figure(figsize=(7,3))            
ax1 = fig.add_subplot(1,3,1)             
ax2 = fig.add_subplot(1,3,2)             
ax3 = fig.add_subplot(1,3,3) 

xs = [x11, x12, x21, x22, x31, x32] 
ys = [y11, y12, y21, y22, y31, y32] 
cs = ['orange', 'blue'] 
ms = 'os' 

for j in xrange(len(xs)): 
    ax1.scatter(xs[j], ys[j], s=50, alpha=0.5, c=cs[j % 2], marker=ms[j % 2]) 
1

我喜欢组织数据和样式,然后使用该组织密谋。生成一些随机数据以生成可运行的示例:

import matplotlib.pyplot as plt 
from numpy.random import random 

fig, axs = plt.subplots(3, figsize=(7,3)) #axs is an array of axes            

orange_styles = {'c':"orange", 'marker':'o'} 
blue_styles = {'c':"blue", 'marker':'s'} 

pts = [] 
for i in range(12): 
    pts.append(random(4)) 

orange_x = pts[0:3] # organized data is lists of lists 
orange_y = pts[3:6] 

blue_x = pts[6:10] 
blue_y = pts[10:12] 

for ax, x, y in zip(axs, orange_x, orange_y): #all the orange cases 
    ax.scatter(x, y, s=50, alpha=0.5, **orange_styles) # **kwds 

for ax, x, y in zip(axs, blue_x, blue_y): 
    ax.scatter(x, y, s=50, alpha=0.5, **blue_styles)