Split bar chart with specific colours for each variable

14 views (last 30 days)
I have 143 data points (neurons) which have "preferred firing directions" (labelled as 1:8 in my 'ydata'). I'm trying to create 6 separate barcharts to show when the neurons have the same firing direction for the 'Go' signal (column 1 of 'ydata') and the 'Instruction' signal (column 2 of 'ydata'). I have tried everything I can think of to label the 'Go' signal with one color and the 'Instruction' signal with another. I know this question has been asked before in slightly different ways, but I've tried a lot of the answers and the best I've got is that it will set all of my bars to the same color and gives me an error whenever I try to index the other color. I'm not sure what I'm doing wrong here.
My dataset is saved in the file 'MatLAB Help.mat' and here is the code I am trying to run:
for k = 1:length(xdata)
if k <= 24
nexttile(1);
hold on
b1 = bar(xdata(k), ydata(k));
b1(1).FaceColor = [0 0.447 0.741];
b1(2).FaceColor = [0.85 0.325 0.098];
elseif k >=25 && k <= 48
nexttile(2);
hold on
bar(xdata(k), ydata(k));
elseif k >= 49 && k <= 72
nexttile(3)
hold on
bar(xdata(k), ydata(k));
elseif k >= 73 && k <= 96
nexttile(4)
hold on
bar(xdata(k), ydata(k));
elseif k >= 97 && k <= 120
nexttile(5)
hold on
bar(xdata(k), ydata(k));
else
nexttile(6)
hold on
bar(xdata(k), ydata(k));
end
end
For some reason, it keeps giving me the error:
Unrecognized property 'FaceColor' for class 'matlab.graphics.GraphicsPlaceholder'.
Any help would be greatly appreciated. Thanks!

Accepted Answer

Voss
Voss on 6 Mar 2024
ydata(k) is a single element of ydata, so
b1 = bar(xdata(k), ydata(k));
produces a single bar, i.e., b1 is of length 1. Trying to access b1(2).FaceColor is what generates the error you got.
If you want two bars, perhaps you mean
b1 = bar(xdata(k), ydata(k,:));
in which ydata(k,:) is the kth row of ydata, so that's a 1x2 vector and b1 is also 1x2.
load('MatLAB Help.mat')
k = 1;
% original generates an error:
figure
b1 = bar(xdata(k), ydata(k))
b1 =
Bar with properties: BarLayout: 'grouped' BarWidth: 0.8000 FaceColor: [0 0.4470 0.7410] EdgeColor: [0 0 0] BaseValue: 0 XData: 1 YData: 1 Use GET to show all properties
try % to catch the error, so subsequent code can execute
b1(1).FaceColor = [0 0.447 0.741];
b1(2).FaceColor = [0.85 0.325 0.098];
catch e % to report the error
disp(e.message);
end
Unrecognized property 'FaceColor' for class 'matlab.graphics.GraphicsPlaceholder'.
% using (k,:) indexing gives two bars
figure
b1 = bar(xdata(k), ydata(k,:))
b1 =
1×2 Bar array: Bar Bar
b1(1).FaceColor = [0 0.447 0.741];
b1(2).FaceColor = [0.85 0.325 0.098];

More Answers (0)

Categories

Find more on Discrete Data Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!