简体   繁体   中英

How can I set the color for all aspects of an axis at once?

I'd like to set the color of major and minor ticks, tick labels, and the axis itself all to the same color, but the only way I've come up with to accomplish this is something like

fig, ax_a_mj = matplotlib.pyplot.subplots()

ax_a_mj.spines['bottom'].set_color('r')
ax_a_mj.tick_params(axis='x', colors='r')
ax_a_mj.tick_params(axis='x', colors='r', which='minor')
ax_a_mj.xaxis.label.set_color('r')

Is there no way to do this with a single statement?

How about the case where I want to do all axes, and I have four:

fig, ax_a_mj = matplotlib.pyplot.subplots()
ax_a_me = ax_a_mj.twinx()
ax_p_mj = ax_a_mj.twiny()

ax_a_mj.spines['bottom'].set_color('r')
ax_a_mj.spines['left'].set_color('r')
ax_a_mj.spines['right'].set_color('r')
ax_a_mj.spines['top'].set_color('r')
ax_a_mj.tick_params(axis='x', colors='r', which='both')
ax_a_mj.tick_params(axis='y', colors='r', which='both')
ax_p_mj.tick_params(axis='x', colors='r', which='both')
ax_a_me.tick_params(axis='y', colors='r', which='both')
ax_a_mj.xaxis.label.set_color('r')
ax_a_mj.yaxis.label.set_color('r')
ax_p_mj.xaxis.label.set_color('r')
ax_a_me.yaxis.label.set_color('r')

If you are doing this a lot, just write your self a helper function

def colorize(ax_in, color_in):
    ax_in.spines['bottom'].set_color(color_in)
    ax_in.tick_params(axis='x', colors=color_in, which='both')
    ax_in.xaxis.label.set_color(color_in)

Note that which can be 'both' which will set both the major and minor ticks (doc) .

If you are using this a lot , you can monkey patch it on to Axes

matplotlib.axes.Axes.my_colorize = colorize

and then

my_ax.my_colorize('r')

should work.

There is on going work to support style sheets by Tony Yu, the first bits of have already been merged into master ( https://github.com/matplotlib/matplotlib/pull/2236 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM