我希望我的 y 轴刻度标签在刻度值为正时为绿色,在刻度值为负时为红色。
考虑以下系列和情节
np.random.seed([3,1415])
pd.Series(np.random.randn(100)).add(.1).cumsum().plot()
我需要 [2, 4, 6, 8] 为绿色,[-2, -4, -6, -8] 为红色。
请您参考如下方法:
您可以通过使用轴的 ax.get_yticklabels() 和 ax.get_yticks() 方法来完成此操作...
import numpy as np
import pylab as plt
import pandas as pd
# figure data
np.random.seed([3,1415])
# create the plot
ax = plt.figure().gca()
ax.plot(pd.Series(np.random.randn(100)).add(.1).cumsum())
# change the y-axis label colors based on positive/negative
a = [ax.get_yticklabels()[i].set_color('red') if (ax.get_yticks()[i] < 0 ) else ax.get_yticklabels()[i].set_color('green') if ( ax.get_yticks()[i] > 0 ) else ax.get_yticklabels()[i].set_color('black') for i in range(len(ax.get_yticklabels()))]
上面使用列表理解[a if A else b if B else c for list]。
