python绘图颜色,在matplotlib中优雅地改变绘图框的颜色

This is a kind of follow-up question to this post, where the coloring of axes, ticks and labels was discussed. I hope it is alright to open a new, extended question for this.

Changing the color of a complete frame (ticks and axes) around a double-plot (via add_subplot) with axes [ax1, ax2] results in a lot of code. This snippet changes the color of the frame of the upper plot:

ax1.spines['bottom'].set_color('green')

ax1.spines['top'].set_color('green')

ax1.spines['left'].set_color('green')

ax1.spines['right'].set_color('green')

for t in ax1.xaxis.get_ticklines(): t.set_color('green')

for t in ax1.yaxis.get_ticklines(): t.set_color('green')

for t in ax2.xaxis.get_ticklines(): t.set_color('green')

for t in ax2.yaxis.get_ticklines(): t.set_color('green')

So for changing the frame color of two plots with two y-axes each, I would need 16(!) lines of code... This is how it looks like:

TsgCB.png

Other methods I dug up so far:

matplotlib.rc: discussed here; changes globally, not locally. I want to have some other plots in different colors. Please, no discussions about too many colors in plots... :-)

matplotlib.rc('axes',edgecolor='green')

dig out the spines of the axis, then change it: also discussed here; not really elegant, I think.

for child in ax.get_children():

if isinstance(child, matplotlib.spines.Spine):

child.set_color('#dddddd')

Is there an elegant way of condensing the above block, something

more "pythonic"?

I'm using python 2.6.5 with matplotlib 0.99.1.1 under ubuntu.

解决方案

Refactoring your code above:

import matplotlib.pyplot as plt

for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'green', 'blue', 'blue']):

plt.setp(ax.spines.values(), color=color)

plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值