get_xticklabels() contains empty text instances

后端 未结 3 1327
生来不讨喜
生来不讨喜 2020-12-07 01:51

I am trying to rotate the x tick labels in a plot. I created a general function that plots in the style I want to plot. I do the following:

labels=ax2.get_xt         


        
相关标签:
3条回答
  • 2020-12-07 01:58

    I will answer according to the title in your question because I don't understand the explanation that follows it.

    The tick labels are not populated until the figure is drawn.

    plt.plot([1, 2])
    ax = plt.gca()
    labels = ax.get_xticklabels()
    for label in labels:
        print(label)
    

    Output:

    Text(0,0,'')
    Text(0,0,'')
    Text(0,0,'')
    Text(0,0,'')
    Text(0,0,'')
    Text(0,0,'')
    Text(0,0,'')
    Text(0,0,'')
    

    When you call plt.draw() the tick labels are populated:

    plt.plot([1, 2])
    ax = plt.gca()
    plt.draw()
    labels = ax.get_xticklabels()
    for label in labels:
        print(label)
    

    Output:

    Text(0,0,'')
    Text(0,0,'0.0')
    Text(0.2,0,'0.2')
    Text(0.4,0,'0.4')
    Text(0.6,0,'0.6')
    Text(0.8,0,'0.8')
    Text(1,0,'1.0')
    Text(0,0,'')
    
    0 讨论(0)
  • 2020-12-07 02:02
    for tl in ax2.get_xticklabels():
        tl.set_rotation(30)
    
    0 讨论(0)
  • 2020-12-07 02:12

    I am not sure if this is the kind of solution you wanted. I had a DataFrame whose x-ticks are all names of different cases. I had to do something like this.

    ax.set_xticks(np.arange(len(my_df.index)))
    ax.set_xticklabels([case for case in my_df.columns], rotation=30)
    
    0 讨论(0)
提交回复
热议问题