How do I color the bars of my stacked bar chart based on another variable?
    10 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    MathWorks Support Team
    
 el 20 de Dic. de 2019
  
    
    
    
    
    Respondida: MathWorks Support Team
    
 el 4 de Mzo. de 2020
            I have created a horizontal bar chart with one stack. I have an array "duration" that describes how wide each bar should be. When I plot the stacked bar chart as below, the colors are assigned automatically:
>> duration = [1 2 3 4 5 4 3 2 1];
>> b = barh(0,duration,'stacked');
However, I want to assign the colors based on another variable, "satisfaction", which is an array of doubles.
>> satisfaction = [12 22 34 42 51 63 77 84 95];
How can I assign colors to my bars based on this array of doubles?
Respuesta aceptada
  MathWorks Support Team
    
 el 20 de Dic. de 2019
        A possible solution is to map your "satisfaction" data onto a colormap, then assign a color to each bar in your chart based on that colormap:
To do so, first set the "FaceColor" of the bars to "flat":
>> ax = axes;
>> b = barh(ax,0,duration,'stacked','FaceColor','flat');
Then, change the axes color limits to match those of your "satisfaction" data:
>> ax.CLim = [min(satisfaction) max(satisfaction)];
To label the colorbar and the x-axis of the plot, we write:
>> c = colorbar;
>> c.Label.String = 'Satisfaction';
>> xlabel('Duration');
Once the colormap is setup, you can assign each bar's "CData" to the corresponding "satisfaction" value:
for i = 1:length(duration)
  b(i).CData = satisfaction(i);
end
This will produce the color mapping you expect. You can also change the scale of the colormap from linear to logarithmic by using the "ColorScale" property on the axes:
For example,
>> ax.ColorScale = "log";
I have attached a file to this post, combining all the steps described above into a single script.
0 comentarios
Más respuestas (0)
Ver también
Categorías
				Más información sobre Orange en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
