Fill box plots with different colors
52 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Addie
am 28 Jan. 2020
Kommentiert: Jakob B. Nielsen
am 28 Jan. 2020
I am trying to make a plot with multiple boxplots where each box is filled with a different color. I found the code at the bottom to do this, but I can't get it to use the colors I want. For example, color(1) gives 0.55 and color(2) gives 0.77, and colors the boxes accordingly, but I want color(1) to be [0.55 0.71 0]. I've been trying to code it in different ways but can't get it to work. Any help would be greatly appreciated.
![weirdfigure.jpg](https://www.mathworks.com/matlabcentral/answers/uploaded_files/268775/weirdfigure.jpeg)
(Ignore the different colored lines around the boxes, they are from trying to use a = get(get(gca,'children'),'children'), which can be used to change the line colors, but not fill colors)
figure(1)
DIC1 = DIC(month==1);
DIC2 = DIC(month==2);
DIC3 = DIC(month==3);
DIC4 = DIC(month==4);
DIC5 = DIC(month==5);
DIC6 = DIC(month==6);
DIC7 = DIC(month==7);
DIC8 = DIC(month==8);
DIC9 = DIC(month==9);
DIC10 = DIC(month==10);
DIC11 = DIC(month==11);
DIC12 = DIC(month==12);
g = [ones(size(DIC1));2*ones(size(DIC2));3*ones(size(DIC3));4*ones(size(DIC4));5*ones(size(DIC5));...
6*ones(size(DIC6));7*ones(size(DIC7));8*ones(size(DIC8));...
9*ones(size(DIC9));10*ones(size(DIC10));11*ones(size(DIC11));12*ones(size(DIC12))];
Months = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
x = [DIC1;DIC2;DIC3;DIC4;DIC5;DIC6;DIC7;DIC8;DIC9;DIC10;DIC11;DIC12];
h = boxplot(x,g,'Labels',Months);
ylabel('DIC (\mumol/kg)')
color = [([0.55 0.71 0]); ([0.55 0.71 0]); ([1 0.2 0]); ([0.4 0.4 0.5]);([0.4 0.4 0.5]); ([1 0.2 0]);([0.6 0.8 1]); ([0.6 0.8 1]);([0.6 0.8 1]);( [0.78 0.26 0.46]);([0.78 0.26 0.46]); ([0.55 0.71 0])];
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),color(j),'FaceAlpha',.5);
end
1 Kommentar
Jakob B. Nielsen
am 28 Jan. 2020
color(1) gives the first entry in color, if color was a vector. But since color is a 12x3 double, what you want is color(1,:) - every column entry in the first row. Or, in your case, color(j,:).
Akzeptierte Antwort
Rik
am 28 Jan. 2020
It looks like g is just a sorted copy of month and x is DIC sorted by month, so why not avoid the numbered variables and use the sort function?
As for your question: adding parentheses during the creation of the color array doesn't make them separate entries. Use color(n,:) instead to select the entire row.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Language Fundamentals finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!