2019年7月4日 星期四

[ Python 常見問題 ] Improve subplot size/spacing with many subplots in matplotlib

Source From Here 
Question 
Very similar to this question but with the difference that my figure can be as large as it needs to be. 

I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using figsave and viewed on a webpage, so I don't care how tall the final image is as long as the subplots are spaced so they don't overlap. No matter how big I allow the figure to be, the subplots always seem to overlap. The example code as below: 
  1. import numpy as np  
  2. import pandas as pd  
  3. import matplotlib.pyplot as plt  
  4.   
  5. # Data  
  6. df=pd.DataFrame({  
  7.     'x': range(1,11),   
  8.     'y1': np.random.randn(10),   
  9.     'y2': np.random.randn(10)+range(1,11),   
  10.     'y3': np.random.randn(10)+range(11,21)   
  11. })  
  12.   
  13. plt.subplot(211)  
  14. plt.plot( 'x''y1', data=df, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)  
  15. plt.title('A tale of 2 subplots (1)')  
  16. plt.ylabel('Count')  
  17.   
  18. plt.subplot(212)  
  19. plt.plot( 'x''y3', data=df, marker='', color='olive', linewidth=2, linestyle='dashed', label="toto")  
  20. plt.title('A tale of 2 subplots (2)')  
  21. plt.ylabel('Count')  
  22. plt.show()  
which will output chart as below with overlapped title and x ticks: 



How-To 
Try using plt.tight_layout. As a quick example: 
  1. import matplotlib.pyplot as plt  
  2.   
  3. fig, axes = plt.subplots(nrows=4, ncols=4)  
  4. fig.tight_layout() # Or equivalently,  "plt.tight_layout()"  
  5.   
  6. plt.show()  
Without Tight Layout: 
 

With Tight Layout : 
 

You can use plt.subplots_adjust to change the spacing between the subplots (source): 
  1. subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)  
The parameter meanings (and suggested defaults) are: 
  1. left  = 0.125  # the left side of the subplots of the figure  
  2. right = 0.9    # the right side of the subplots of the figure  
  3. bottom = 0.1   # the bottom of the subplots of the figure  
  4. top = 0.9      # the top of the subplots of the figure  
  5. wspace = 0.2   # the amount of width reserved for blank space between subplots  
  6. hspace = 0.2   # the amount of height reserved for white space between subplots  
The actual defaults are controlled by the rc file. So we can modify the original code to be: 
  1. import numpy as np  
  2. import pandas as pd  
  3. import matplotlib.pyplot as plt  
  4.   
  5. # Data  
  6. df=pd.DataFrame({  
  7.     'x': range(1,11),   
  8.     'y1': np.random.randn(10),   
  9.     'y2': np.random.randn(10)+range(1,11),   
  10.     'y3': np.random.randn(10)+range(11,21)   
  11. })  
  12.   
  13. plt.subplot(211)  
  14. plt.plot( 'x''y1', data=df, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)  
  15. plt.title('A tale of 2 subplots (1)')  
  16. plt.ylabel('Count')  
  17.   
  18. plt.subplot(212)  
  19. plt.plot( 'x''y3', data=df, marker='', color='olive', linewidth=2, linestyle='dashed', label="toto")  
  20. plt.title('A tale of 2 subplots (2)')  
  21. plt.ylabel('Count')  
  22. plt.subplots_adjust(hspace = 0.5)  # <-- between="" increase="" nbsp="" plot="" space="" span="" sub="" the="">
  23. plt.show()  
To have below chart: 


Supplement 
Multiple lines chart

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...