2021年2月7日日曜日

matplotlib

matplotを利用する際、毎回どこかの例をコピペするので、ココにまとめておきます。
今後、追加していきましょう。

  1. import matplotlib.pyplot as plt
  2. import matplotlib.ticker as ticker
  3. from matplotlib.font_manager import FontProperties
  4. fp=FontProperties(fname='c:/WINDOWS/Fonts/msgothic.ttc',size = 10)
  5. #fp=FontProperties(fname='./font/TakaoGothic.ttf')
  6. #import japanize_matplotlib
  7. #import seaborn as sns
  8. #sns.set(font="IPAexGothic")
  9.  
  10. #####################################################
  11. #ヒストグラム
  12. #CDF(2軸)
  13. #凡例は外側に配置、透明度0
  14. #####################################################
  15.  
  16. def plot_hist(col,SaveFName):
  17. data=df[col]
  18. fig, ax1 = plt.subplots()
  19. ax2 = ax1.twinx()
  20.  
  21. # histogram
  22. n, bins, patches = ax1.hist(data,
  23. bins=200,
  24. #density=True,
  25. #cumulative=True,
  26. range=[-100,100],
  27. alpha=0.7,
  28. label='頻度')
  29. # another y-axis
  30. y2 = np.add.accumulate(n) / n.sum()
  31. x2 = np.convolve(bins, np.ones(2) / 2, mode="same")[1:]
  32.  
  33. lines = ax2.plot(x2, y2, ls='-',
  34. color='r',
  35. #marker='o',
  36. label='累積分布')
  37. # set axis
  38. ax1.set_xlim(-100, 100)
  39. ax1.set_ylim(0, ylim)
  40. ax2.set_ylim(0, 1.05)
  41. #ax2.yaxis.set_major_locator(ticker.MultipleLocator(0.2))
  42. ax1.grid(visible=True)
  43. ax1.set_axisbelow(True)
  44.  
  45. # legend
  46. handler1, label1 = ax1.get_legend_handles_labels()
  47. handler2, label2 = ax2.get_legend_handles_labels()
  48. ax1.legend(handler1 + handler2,
  49. label1 + label2,
  50. loc=2,
  51. shadow=True,
  52. #borderaxespad=0.
  53. prop=fp
  54. )
  55.  
  56. ax1.set_xlabel(col, fontproperties=fp)
  57. ax1.set_ylabel('頻度', fontproperties=fp)
  58. ax2.set_ylabel('累積確率', fontproperties=fp)
  59. plt.savefig('./output/'+SaveFName+'.png',
  60. format='png',
  61. dpi=300)
  62. plt.show()
  63.  
  64.  
  65. #####################################################
  66. #棒グラフ
  67. #CDF(2軸)
  68. #凡例は外側に配置、透明度0
  69. #####################################################
  70.  
  71. fig, ax1 = plt.subplots(figsize=(6,3))
  72. ax2 = ax1.twinx()
  73. i=0
  74. for col, data in df.iteritems():
  75. data_sum=data.sum()
  76. data1=data.div(data_sum)
  77. data_cum = data1.cumsum()
  78. bar= ax1.bar(df.index+0.4*i,
  79. data,
  80. width=0.4,
  81. align='edge',
  82. label=str(col))
  83. line = ax2.plot(df.index+0.5,
  84. data_cum,
  85. ls='--',
  86. #marker='o',
  87. #color='r'
  88. label='累積'+str(col))
  89. i=i+1
  90. # set axis
  91. ax1.set_xlim(10, 100)
  92. ax1.set_ylim(0, 105)
  93. ax2.set_ylim(0, 1.05)
  94. ax1.grid(visible=True)
  95. ax1.set_axisbelow(True)
  96.  
  97. # legend
  98. handler1, label1 = ax1.get_legend_handles_labels()
  99. handler2, label2 = ax2.get_legend_handles_labels()
  100. ax1.legend(handler1 + handler2,
  101. label1 + label2,
  102. bbox_to_anchor=(1.15, 1.02),
  103. loc='upper left',
  104. shadow=True,
  105. #borderaxespad=0.
  106. prop=fp
  107. ).get_frame().set_alpha(1.0)
  108.  
  109. ax1.set_xlabel('aaa', fontproperties=fp)
  110. ax1.set_ylabel('bbb', fontproperties=fp)
  111. ax2.set_ylabel('ccc', fontproperties=fp)
  112.  
  113. plt.savefig('./output/ddd.png',
  114. format='png',
  115. bbox_inches='tight',
  116. dpi=300)
  117.  
  118.  
  119. #####################################################
  120. #折れ線(マーカーのみの散布図)
  121. #移動平均
  122. #dfのカラムを順にプロット
  123. #散布図と移動平均の色を合わせる
  124. #####################################################
  125.  
  126. def plot_rolling(df, SaveFName):
  127. fig, ax1 = plt.subplots()
  128.  
  129. for i in range(df.shape[1]):
  130. lines = ax1.plot(df.index,df.iloc[:,i],
  131. ls=' ',
  132. color='C'+str(i),
  133. marker='o',
  134. label=df.columns[i])
  135.  
  136. for i in range(df_rate.shape[1]):
  137. s=df.iloc[:,i].rolling(window=10).mean()
  138. lines = ax1.plot(df.index-4.5,s,
  139. ls='-',
  140. color='C'+str(i),
  141. #marker='o',
  142. label='移動平均'+str(df.columns[i]))
  143.  
  144. # set axis
  145. ax1.set_xlim(0, 50)
  146. ax1.set_ylim(0, 0.05)
  147. ax1.grid(visible=True)
  148. ax1.set_axisbelow(True)
  149.  
  150. # legend
  151. ax1.legend(bbox_to_anchor=(1.05, 1), loc='upper left',prop=fp)
  152.  
  153. ax1.set_xlabel('aaa', fontproperties=fp)
  154. ax1.set_ylabel('bbb', fontproperties=fp)
  155.  
  156. plt.savefig('./output/'+SaveFName+'.png',
  157. format='png',
  158. bbox_inches='tight',
  159. dpi=300)

0 件のコメント:

コメントを投稿