ZK Zhao
ZK Zhao

Reputation: 21613

Matplotlib & Python: assign a color when doing iterateive plotting

I have a group of ellipses to plot, but the ellipses would be plotted in the same color. This makes it hard to differentiate one from another:

# import matplotlib as mpl
# from matplotlib import pyplot as plt

def plot_ellpises(ell_groups):
    print 'GMM Plot Result'
    fig, ax = plt.subplots()
    for ell in ell_groups:
        xy, width, height, angle = ell
        ell = mpl.patches.Ellipse(xy=xy, width=width, height=height, angle = angle)
        ell.set_alpha(0.5)
        ax.add_patch(ell)
    ax.autoscale()
    ax.set_aspect('equal')
    return plt.show() 

ell1= [-7.13529086, 5.28809598], 4.42823535, 5.97527801,107.60800706
ell2= [.96850139, 1.33792516], 5.73498868,8.98934084,97.8230716191
ell3= [1.43665497, 3.87692805], 1.42859078, 1.95525638,83.135072216
ell_groups = [ell1,ell2,ell3]
plot_ellpises(ell_groups)

enter image description here

I want to know how can I assign a color to each when plotting, so the ellpises would be easier to look at.

Upvotes: 0

Views: 99

Answers (1)

xnx
xnx

Reputation: 25560

You can access Matplotlib's color-cycle with ax._get_lines.color_cycle. This is an iterator, so call next() on it each time you draw an ellipse:

def plot_ellpises(ell_groups):
    print 'GMM Plot Result'
    fig, ax = plt.subplots()
    colors = ax._get_lines.color_cycle
    for ell in ell_groups:
        xy, width, height, angle = ell
        ell = mpl.patches.Ellipse(xy=xy, width=width, height=height,
                                  angle = angle, facecolor=next(colors))
        ell.set_alpha(0.5)
        ax.add_patch(ell)
    ax.autoscale()
    ax.set_aspect('equal')
    return plt.show() 

enter image description here

To specify the colors cycled through, you can set them explicitly as rcParams before plotting. e.g., for magenta, red, yellow:

mpl.rcParams['axes.color_cycle'] = ['m', 'r', 'y']

enter image description here

Upvotes: 2

Related Questions