nos
nos

Reputation: 20862

python matplotlib plotting many subfigures with the same parameters

My plot is like the following

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')

It seems kinda redundant to set s=50, alpha=0.5 over and over. Is there a way to set them once for all? Also for color and marker, is there a way to write them in one place so it's easier to modify?

Upvotes: 2

Views: 90

Answers (2)

cphlewis
cphlewis

Reputation: 16239

I like organizing the data and styles, and then using that to organize the plotting. Generating some random data to make a runnable example:

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)

Upvotes: 1

Julien Spronck
Julien Spronck

Reputation: 15423

You could do this:

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])

Upvotes: 3

Related Questions