凡例の線を短くする函数
最終更新:2021/07/14
MATLABで作った図ってときどき, 凡例のラインが長すぎる. これを短くするための函数.
使い方
例えば, 以下の図に,

legend('Sound', 'Vibration', 'Box', 'off')
として凡例を入れると

そこで, この関数shortenLegendLine
を使う.
凡例を入れる際に,
MATLAB
[l, p] = legend('Sound', 'Vibration', 'Box', 'off'); % このような戻り値でlegendをいれる. % ラインの長さを1/n倍にしたいとして, pとnを引数にする. shortenLegendLine(p, 2)

コード
たいして複雑な函数ではない.
legendを入れる際に[l, p]
を戻り値にするのがコツ.
この函数ではBoxまで短くはならんけど, まあ, かんたんにそれもできるだろう.
MATLAB
function [] = shortenLegendLine(p, nDivide) % SHORTENLEGENDLINE makes legend line short by nDivide times. % You can get p as follows: % [l, p] = legend('a', 'b', ...) nClass = length(p); for iClass = 1:nClass if isa(p(iClass), 'matlab.graphics.primitive.Line') if length(p(iClass).XData) == 2 X = p(iClass).XData; X(1) = X(2) - (X(2) - X(1))/nDivide; p(iClass).XData(1) = X(1); end end end end