How do I format axis ticks to be a certain color based on sign?

前端 未结 1 1304
日久生厌
日久生厌 2021-01-16 06:04

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

         


        
相关标签:
1条回答
  • 2021-01-16 06:47

    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].

    0 讨论(0)
提交回复
热议问题