python:matplotlib

matplotlib

Qiitaに良い記事を見つけたので、メモ。初めてmatplot使うときにすごくわかりやすかったです。ほとんど馬場の忘備録ですが、論文とかでグラフ作成の必要が出たときに見返して大事な部分だけをさらえる内容にしています。

棒グラフのサンプルです。各barに数値をいれて、ラベルを90度回転させてる例。matplotlibはversion3.3以上を利用してください。

simple_barplotpy
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
 
 
def autolabel(rects, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.
 
    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """
 
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0, 'right': 1, 'left': -1}
 
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(offset[xpos]*3, 0),  # use 3 points offset
                    textcoords="offset points",  # in both directions
                    ha=ha[xpos], va='bottom')
 
 
# plotting data
plot_data = [20, 35, 30, 35, 27, 50, 35, 30, 35, 27]
x_labels = ['G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10']
index = np.arange(len(plot_data))  # the x locations for the groups
width = 0.35  # the width of the bars
 
 
fig, ax = plt.subplots(figsize=(15, 4.0))
 
rects = ax.bar(index, plot_data, width, label='Men')
ax.set_box_aspect(0.2)
ax.autoscale()
 
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group')
ax.set_xticks(index)
ax.set_xticklabels(x_labels)
ax.legend()
 
autolabel(rects, "center")
 
fig.tight_layout()
plt.margins(0.01, 0.1)
plt.subplots_adjust(bottom=0.10)
# plt.grid(True)
plt.xticks(index, x_labels, rotation='vertical')
plt.savefig('barplot.png', dpi=72)
plt.show()

箱ひげ図を描く最小のサンプルは次の通り。

simple_boxplot.py
test
  • /home/users/2/lolipop.jp-4404d470cd64c603/web/ws/data/pages/python/matplotlib.txt
  • 最終更新: 2020/10/15 15:53
  • by baba