2016-08-03 84 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)