Guest User

Untitled

a guest
Feb 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. # matplotlib無法顯示中文字的問題
  2. import matplotlib
  3. import matplotlib.pyplot as plt
  4. from matplotlib import font_manager
  5. microhei = matplotlib.font_manager.FontProperties(fname='wqy-microhei.ttc')
  6.  
  7. def get_all_text(obj):
  8. '''
  9. Get all text objects in a matplotlib Figure
  10. Helper for plt_show_ch
  11. '''
  12. queue = [obj]
  13. all_text = []
  14. while queue:
  15. currobj = queue.pop(0)
  16. if isinstance(currobj, matplotlib.text.Text):
  17. all_text.append(currobj)
  18. else:
  19. queue = queue + currobj.get_children()
  20. return all_text
  21.  
  22. def plt_show_ch():
  23. '''代替 plt.show()
  24. 在 show 之前先把所有 Text 物件設定好用中文字體
  25. '''
  26. fig = plt.gcf()
  27. for textobj in get_all_text(fig):
  28. fontsize = textobj.get_fontsize()
  29. textobj.set_fontproperties(microhei)
  30. textobj.set_fontsize(fontsize)
  31. return plt.show()
Add Comment
Please, Sign In to add comment