10

I am following the tutorial from here: https://matplotlib.org/gallery/ticks_and_spines/multiple_yaxis_with_spines.html
However, the example used is for a single plot and I'm currently working with subplots. My version is the following:

    p1 = tr[names['equity']].plot(ax=ax3, linewidth = 0.75)
    axb = ax3.twinx()
    axb.spines["right"].set_position(("axes", 0.5))
    p2 = tr[names[local_rating]].plot(ax=axb, c= 'r', linewidth = 0.75)
    axb.grid(False)
    axb.margins(x=0)
    axc = ax3.twinx()    
    p3 = tr[names['vol']].plot(ax=axc, c = 'g', linewidth = 0.75)
    axc.grid(False)
    axc.margins(x=0)
    ax3.yaxis.label.set_color(p1.get_color())
    axb.yaxis.label.set_color(p2.get_color())
    axc.yaxis.label.set_color(p3.get_color())

When I try to do pX.get_color() I get:

AttributeError: 'AxesSubplot' object has no attribute 'get_color'

My question is: what method should I use to recover a subplot's color?

I'm aware that I could manually set the color to match since it's a small number of instructions, but I'm just wondering if there is another way.

Thanks

1
  • 1
    I was working with ax.bar and wanted to get the latest color. Here's what did it for me in case anyone else runs into the same issue bars = ax.bar(x, height) and c = bars.patches[-1].get_facecolor() Commented Jan 29, 2020 at 15:49

1 Answer 1

14

This has nothing to do with subplots. You are using the pandas plotting function instead of the matplotlib plot function as in the example.

An axes indeed has no color. If you are interested in the color of the lines inside the axes you may use e.g.

ax.get_lines()[0].get_color()

to get the color of the first line in the axes ax.

Sign up to request clarification or add additional context in comments.

2 Comments

you're correct, changing to axX.get_lines()[0].get_color() works correctly now, thank you!
If you keep adding lines and want to get the color of the last line, use: ax.lines[-1].get_color()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.