如何根据符号将轴刻度线格式化为某种颜色? [英] How do I format axis ticks to be a certain color based on sign?
本文介绍了如何根据符号将轴刻度线格式化为某种颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望当刻度值为正时,我的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表示A否则b表示b否则c表示列表].
I want my y-axis tick labels to be green when tick values are positive and red when tick values are negative.
Consider the following series and plot
np.random.seed([3,1415])
pd.Series(np.random.randn(100)).add(.1).cumsum().plot()
I need the [2, 4, 6, 8]
to be green and [-2, -4, -6, -8]
to be red.
解决方案
You can accomplish this by using using the ax.get_yticklabels() and ax.get_yticks() methods of an axis...
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()))]
The above uses the list comprehension [a if A else b if B else c for list].
这篇关于如何根据符号将轴刻度线格式化为某种颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文