無地のノート

なんでも書きます

matplotlibの線種(linestyle)を自動で変えてplot

1番目のforの中で処理.

import matplotlib.pyplot as plt

matplotlib.rcParams['font.family'] = 'Times New Roman' #使用するフォント名
#フォント設定準備
fontprop = matplotlib.font_manager.FontProperties(fname = "C:\\Windows\\Fonts\\times.ttf")
fontsize = 16
#1. 
fig = plt.figure(dpi=100)
#2. 
ax1 = fig.add_subplot(111) #(行数, 列数, 何番目のプロットか)
for val in vals: #valsはプロットすべき系列が順に入っているlist.例: [val1, val2, val3],val[0]がxでval[1]がy(xとyはリスト)など.
    id = vals.index(val) #valはvals[id]に入っている
    linestyles = ["-", "--", "-.", ":", ".", ","]
    if len(linestyles) - 1 < id:
        linestyle = linestyles[id%(len(linestyles))] #len=6なら(012345)0123450...となる
    else:
        linestyle = linestyles[id]
        pass
    #3.
    ax1.plot(val[0], val[1], color="black", linewidth=2.5, linestyle=linestyle, marker= "o")
    pass
ax1.set_xlim(min(val[0])*1.1, max(val[0])*1.1) #左右に余裕を持たせる
ax1.set_ylim(min(val[1])*1.1, max(val[1])*1.1) #上下に余裕を持たせる
for label in (ax1.get_xticklabels() + ax1.get_yticklabels()): #Textインスタンスのフォントプロパティを変更
    label.set_fontname('Times New Roman')
    label.set_fontsize(fontsize)
    pass
ax1.legend(loc='upper right')
#目盛りが入る場所
plt.xticks(range(0, 100, 5))
plt.yticks(range(0, 100, 5))
plt.xlabel("X", fontsize = 20, fontdict = {"fontproperties": fontprop})
plt.ylabel("Y", fontsize = 20, fontdict = {"fontproperties": fontprop})
plt.tight_layout()
plt.savefig('fig.png')
plt.show()