Bof*_*fin 24 python colors matplotlib
这是这篇文章的一个后续问题,其中讨论了轴,刻度和标签的着色.我希望为此开一个新的,扩展的问题是可以的.
add_subplot使用轴[ax1,ax2] 围绕双图(通孔)更改完整框架(刻度线和轴)的颜色会产生大量代码.此代码段会更改上图的框架颜色:
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')
Run Code Online (Sandbox Code Playgroud)
因此,为了改变两个图的帧颜色,每个两个y轴,我需要16(!)行代码...这是它的样子:

到目前为止我挖出的其他方法:
matplotlib.rc:这里讨论; 全球而非本地变化.我想要一些不同颜色的其他情节.请不要在情节中讨论太多颜色...... :-)
matplotlib.rc('axes',edgecolor='green')
Run Code Online (Sandbox Code Playgroud)挖出轴的刺,然后改变它:这里也讨论过 ; 我觉得并不是很优雅.
for child in ax.get_children():
if isinstance(child, matplotlib.spines.Spine):
child.set_color('#dddddd')
Run Code Online (Sandbox Code Playgroud)是否有一种优雅的方式来凝聚上面的块,更多的是"pythonic"?
我在ubuntu下使用python 2.6.5和matplotlib 0.99.1.1.
Chr*_*lis 19
重构上面的代码:
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)
Run Code Online (Sandbox Code Playgroud)
Joe*_*ton 15
假设您正在使用matplotlib(> = 1.0)的合理最新版本,可能尝试这样的事情:
import matplotlib.pyplot as plt
# Make the plot...
fig, axes = plt.subplots(nrows=2)
axes[0].plot(range(10), 'r-')
axes[1].plot(range(10), 'bo-')
# Set the borders to a given color...
for ax in axes:
ax.tick_params(color='green', labelcolor='green')
for spine in ax.spines.values():
spine.set_edgecolor('green')
plt.show()
Run Code Online (Sandbox Code Playgroud)

也许回答我自己的问题有点粗糙,但我想分享到目前为止我能找到的东西.此版本可以为两个带有轴[ax1, ax2]和[ax3, ax4]两种不同颜色的子图标着色.这是很多比16行我在我的问题表述短.它的灵感来自Joe Kington在这里的回答以及twinx杀死刻度标签的颜色.
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
num = 200
x = np.linspace(501, 1200, num)
yellow_data, green_data , blue_data= np.random.random((3,num))
green_data += np.linspace(0, 3, yellow_data.size)/2
blue_data += np.linspace(0, 3, yellow_data.size)/2
fig = plt.figure()
plt.subplot(211) # Upper Plot
ax1 = fig.add_subplot(211)
ax1.fill_between(x, 0, yellow_data, color='yellow')
ax2 = ax1.twinx()
ax2.plot(x, green_data, 'green')
plt.setp(plt.gca(), xticklabels=[])
plt.subplot(212) # Lower Plot
ax3 = fig.add_subplot(212)
ax3.fill_between(x, 0, yellow_data, color='yellow')
ax4 = ax3.twinx()
ax4.plot(x, blue_data, 'blue')
# Start coloring
for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'green', 'blue', 'blue']):
for ticks in ax.xaxis.get_ticklines() + ax.yaxis.get_ticklines():
ticks.set_color(color)
for pos in ['top', 'bottom', 'right', 'left']:
ax.spines[pos].set_edgecolor(color)
# End coloring
plt.show()
Run Code Online (Sandbox Code Playgroud)

我认为这是被接受的,因为它是迄今为止我能找到的最紧凑的解决方案.尽管如此,我仍然愿意接受其他方式,也许是更优雅的解决方法.