Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib get_color for subplot

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

like image 268
Yuca Avatar asked Aug 27 '18 15:08

Yuca


People also ask

How do I create a legend for a subplot in MatPlotLib?

MatPlotLib with Python Create a figure and a set of subplots, using the subplots() method, considering 3 subplots. Plot the curve on all the subplots(3), with different labels, colors. To place the legend for each curve or subplot adding label. To activate label for each curve, use the legend() method.

How do I create a multi legend in MatPlotLib?

MatPlotLib with PythonPlace the first legend at the upper-right location. Add artist, i.e., first legend on the current axis. Place the second legend on the current axis at the lower-right location. To display the figure, use show() method.

Which method is used to add title to the subplots using MatPlotLib?

We can also add title to subplots in Matplotlib using title. set_text() method, in similar way to set_title() method.


1 Answers

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.

like image 142
ImportanceOfBeingErnest Avatar answered Oct 21 '22 17:10

ImportanceOfBeingErnest