LoginSignup
5
1

More than 1 year has passed since last update.

[MATLAB] 棒グラフにcolormapを適用する

Last updated at Posted at 2021-09-04

本記事では,

  • MATLAB R2021a

を使用しています.

はじめに

MATLABにはたくさんのplotが用意されています. その多くは, colormapなどに対応しており, カラフルな図を作成することができます. しかし, bar関数histogram関数ではカラフルな図が作りづらい気がする. そこで, 今回は, 棒グラフにcolormapを適用してカラフルなヒストグラムを作成することを考えた.

データの作成

今回は以下のコマンドでデータを作成した.

matlab
numData = 10000; % Set number of Data
range = 10; % Set Data Range
Data = range*randn(1,numData) % Create Data

次に, このデータからヒストグラムデータをhistcounts関数で作成する. 今回は0.1ずつに分けてヒストグラムデータを作成した.

matlab
[N,edges] = histcounts(Data,'BinWidth',0.1);

これをbar関数で棒グラフにすると以下のようになる.

matlab
figure
b1 = bar(edges(1:end-1),N);

twitter1_qiita_start.png

x軸に沿ったcolormap表示

matlab
figure
b = bar(edges(1:end-1),N,1,'FaceColor','flat','EdgeColor','none');

%{
If you want to set "xlim" or/and "ylim", please write here!!
%}

まずは, $x$軸の値に沿って棒グラフにcolormapから得た色を付加していく. ここではcolormapとしてjetを採用した.

matlab
cmap = colormap(jet);
ax = gca;
xrange = ax.XLim; % Get bar Graph x-range
for i = 1:length(N)
    tmp = (edges(i)-xrange(1))/(xrange(2)-xrange(1)); % Normalize to follow the x-range
    color_num = round(length(cmap)*tmp); % Normalize Color Number

    % Get color from colormap
    if (color_num < 1)
        b.CData(i,:) = cmap(1,:);
    elseif (color_num > length(cmap))
        b.CData(i,:) = cmap(end,:);
    else
        b.CData(i,:) = cmap(color_num,:);
    end
end

ここにcolorbarも追加すると以下のようになる.

matlab
colorbar('southoutside','ticks',[]);

twitter1_qiita_x.png
上図のようにcolorbarと棒グラフの色が対応していることがわかる.

y軸に沿ったcolormap表示

matlab
figure
b = bar(edges(1:end-1),N,1,'FaceColor','flat','EdgeColor','none');

%{
If you want to set "xlim" or/and "ylim", please write here!!
%}

ここでもcolormapとしてjetを採用する. そして, $y$軸の範囲に対応させて, 各データに対応した色を付加していく.

matlab
cmap = colormap(jet);
ax = gca;
yrange = ax.YLim; % Get bar Graph y-range
for i = 1:length(N)
    tmp = (N(i)-yrange(1))/(yrange(2)-yrange(1)); % Normalize to follow the y-range
    color_num = round(length(cmap)*tmp); % Normalized Color Number

    % Get color from colormap
    if (color_num < 1)
        b.CData(i,:) = cmap(1,:);
    elseif (color_num > length(cmap))
        b.CData(i,:) = cmap(end,:);
    else
        b.CData(i,:) = cmap(color_num,:);
    end
end

ここに, colorbarも付加すると, 以下のようなグラフが得られる.

matlab
colorbar('eastoutside','ticks',[]);

twitter1_qiita_y.png

おわりに

本記事は以下を参考にさせていただいた.

MATLAB Answers

Bar plot with color map

MATLAB Documentation

bar
histogram
histcounts
colormap
colorbar
Axesのプロパティ

また, 本記事のアイデアをくださった質問者の方に, 心より感謝申し上げます.

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1