2018年10月9日 星期二

[ Python 常見問題 ] matplotlib - Modify tick label text

Source From Here 
Question 
I want to make some modifications to a few selected tick labels in a plot. For example, if I do: 
  1. label = axes.yaxis.get_major_ticks()[2].label  
  2. label.set_fontsize(size)  
  3. label.set_rotation('vertical')  
the font size and the orientation of the tick label is changed. However, if try: 
  1. label.set_text('Foo')  
the tick label is not modified. Also if I do: 
  1. print label.get_text()  
So how exactly can I modify the tick label text? 

How-To 
Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than 1.1.0. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may not be... 

Normally, you'd do something along these lines: 
  1. """  
  2. Simple demo of a scatter plot.  
  3. """  
  4. import numpy as np  
  5. import matplotlib.pyplot as plt  
  6.   
  7. fig, ax = plt.subplots()  
  8.   
  9. N = 50  
  10. x = np.random.rand(N)  
  11. y = np.random.rand(N)  
  12. colors = np.random.rand(N)  
  13. area = np.pi * (15 * np.random.rand(N))**2  # 0 to 15 point radii  
  14.   
  15. plt.scatter(x, y, s=area, c=colors, alpha=0.5)  
  16.   
  17. # We need to draw the canvas, otherwise the labels won't be positioned and   
  18. # won't have values yet.  
  19. fig.canvas.draw()  
  20. labels = [item.get_text() for item in ax.get_xticklabels()]  
  21. print("xtick labels: {}".format(labels))  
  22. labels[1] = 'Testing'  # The second x tick label text is modified to be "Testing"  
  23.   
  24. ax.set_xticklabels(labels)  
  25.   
  26. plt.show()  
Output: 

沒有留言:

張貼留言

[Linux 常見問題] How to set a file size limit for a directory?

Source From   Here   Question   I   have a directory on my system which is used for a specific reason by applications and users , but I   d...