Plot stacked bar chart with legends (2024)

38 views (last 30 days)

Show older comments

AHMED FAKHRI on 22 May 2021

  • Link

    Direct link to this question

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends

  • Link

    Direct link to this question

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends

Commented: Adam Danz on 23 May 2021

Accepted Answer: Adam Danz

  • emissions_sectors2.xlsx

Open in MATLAB Online

Hi All

I have the atatched Excel sheet and I want please to plot a stacked bar chart in every year (2025, 2030, 2040, 2050) according to the three techs (electrics, H2, CCS+BECCS). I want the legends to be unique in terms of the colour and do not change if the year or the tech is changed which is where I mostly struggeling.

I don't mind using other plotting method if easier.

I tried using the following code but the legends will be different for each sector.

bar(1,[E25{:,2}],'stacked')

tech=['Electric'];

set(gca,'xticklabel',tech)

legend (E25{:,1})

hold on

bar(2,[H25{:,2}],'stacked')

tech2=['Hydrogen'];

set(gca,'xticklabel',tech2)

hold on

bar(3,[CCS25{:,2}],'stacked')

tech3=['CCS+BECCS'];

set(gca,'xticklabel',tech3)

The final graph should looks like this:

Plot stacked bar chart with legends (2)

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

Sign in to answer this question.

Accepted Answer

Adam Danz on 22 May 2021

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#answer_705908

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#answer_705908

Edited: Adam Danz on 22 May 2021

Open in MATLAB Online

Legend demo

Create the bar plots and assign the bar colors. Combine the bar handles within the same legend and specify the legend strings. This is done with tiledlayout where you can more easily control the position of a global legend.

rng('default')

x1 = rand(3,8);

x2 = rand(4,10);

fig = figure();

fig.Position(3:4) = [725,420];

tiledlayout(1,2)

nexttile

bh1 = bar(x1,'stacked');

colors1 = mat2cell(lines(numel(bh1)),ones(numel(bh1),1), 3);

set(bh1, {'CData'}, colors1)

nexttile

bh2 = bar(x2,'stacked');

set(bh2,'FaceColor','flat');

colors2 = mat2cell(colorcube(numel(bh2)),ones(numel(bh2),1), 3);

% Define one label per bar handle

legHandles = [bh1, bh2];

labels = ["Cement","Ethylene","Glass","Lime","Gas","Oil","Paper","Vehicles","Coal",...

"Ammonia","Shale Gas","NRMM","Foo","Bar","Other","Gluposti","Waste","Refining"];

lg = legend(legHandles,labels,'Orientation','Horizontal','NumColumns',6);

lg.Layout.Tile = 'North';

Plot stacked bar chart with legends (4)

Colorbar demo

rng('default')

x1 = rand(3,8);

x2 = rand(4,10);

fig = figure();

fig.Position(3:4) = [725,420];

tiledlayout(1,2)

nexttile

bh1 = bar(x1,'stacked');

colors1 = mat2cell(lines(numel(bh1)),ones(numel(bh1),1), 3);

set(bh1, {'CData'}, colors1)

nexttile

bh2 = bar(x2,'stacked');

set(bh2,'FaceColor','flat');

colors2 = mat2cell(colorcube(numel(bh2)),ones(numel(bh2),1), 3);

set(bh2, {'CData'}, colors2)

% Define one label per color

allColors = [vertcat(colors1{:}); vertcat(colors2{:})];

labels = ["Cement","Ethylene","Glass","Lime","Gas","Oil","Paper","Vehicles","Coal",...

"Ammonia","Shale Gas","NRMM","Foo","Bar","Other","Gluposti","Waste","Refining"];

% Combine bar color and use them to define the colormap

ax = gca;

ax.Colormap = allColors;

cb = colorbar();

cmapInterval = 1/size(allColors,1);

cb.Ticks = cmapInterval/2 : cmapInterval : 1;

cb.TickLabels = labels;

Plot stacked bar chart with legends (5)

8 Comments

Show 6 older commentsHide 6 older comments

AHMED FAKHRI on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536058

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536058

Edited: AHMED FAKHRI on 22 May 2021

Many thanks @Adam Danz for your help, I really appreciate your time.

i think the bar graphs produced not corresponding to what I want. It is may be my fault for not explaining it well.

There should be 4 bar graphs:

1- 2025 for electric, H2, CCS+BECCS on x-axis. y-axis represents the stacked values by each sector.

2- 2030 for electric, H2, CCS+BECCS on x-axis.

3- 2040 for electric, H2, CCS+BECCS on x-axis.

4- 2050 for electric, H2, CCS+BECCS on x-axis.

The legends in all of the four graphs should be the same colour per sector.

Please see the 4 bar graphs required:

Plot stacked bar chart with legends (7)

Plot stacked bar chart with legends (8)

Plot stacked bar chart with legends (9)

Plot stacked bar chart with legends (10)

Adam Danz on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536118

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536118

Open in MATLAB Online

How are you producing the bar plots? If you included the lines of code that read-in the data and produce the input variables in your question I could run the code but I don't know what those values are.

The order of the stacked colors should be the same for each stacked-bar unless you're manually changing the colors. If there are any missing data (NaN) those colors should automatically be excluded. For example, the 2nd bar below is missing the 2nd sector (orange).

x = rand(4,3);

x(2,2) = NaN;

AHMED FAKHRI on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536133

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536133

Many thanks @Adam Danz again.

Let me please explain to you what each bar graph represents.

Let us simplify the issue by taking the data for 2025 only.

In this year, 2025, there are a number of industrial sectors ( coal mine, food&drink, etc) that use technologies to decarbonise its processes. these technologies actually are using electricity (electric), or using Hydrogen (H2) or using carbon capture and storage (CCS).

Therefore, looking at the data (Excel sheet ) for 2025, the electric bar should aggregate the emissions for:

'Coal Mine (open)' , 'Food & Drink' , , Gas Platform' , 'Gas Terminal' , 'Glass' , NRMM' , 'Oil Terminal'

'Other Chemicals' , 'Other Iron and Steel' , 'Other industry' , 'Paper' , 'Vehicles'

the total sum is 0.603913 MtCO2e

Similarly, for 2025, the H2 bar should aggreagte: NRMM, 'Other Chemicals', and 'Vehicles',

the CCS+BECCS should aggregate: 'Paper, 'ammonia' and 'Refining'.

If we see now the 2025 total stacked bar graph below:, it is clear that the Electric bar reaches around 0.6 as a total from 12 sectors (as above) with each sector has a different colour.

Now when plotting for the year 2030, 2040, 2050, similar bar graphs should appear however the colour for the sectors used in 2025 should not change, otherwise it causes confusion.

Plot stacked bar chart with legends (14)

AHMED FAKHRI on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536203

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536203

Oh, I just realised that your code does not take into account the Excel sheet (data I want to plot) which I attached in the post?

Adam Danz on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536208

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536208

Edited: Adam Danz on 22 May 2021

The code in your example doesn't include code needed to read in the file and doesn't define variables E25, H25, etc. I've learned not to invest too much time into guessing what someone is doing, especially when the problem appears to be with that process.

You mentioned that the 2025 Electric bar should sum to 0.603913 but clearly it isn't higher than ~.58 according to the image you shared in the comment above.

That indicates that the estimate of 0.603913 is off or the bar input data are not correct.

The colors in your plots also indicate that you are changing the bar colors which isn't shown in your code either. For example, why are the first stack of bars for Electric and Hydro light green but CCS is darker green? That's not default Matlab behavior.

Adam Danz on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536218

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536218

Edited: Adam Danz on 22 May 2021

Open in MATLAB Online

Your table consists of 26 rows or sectors.

This demo quickly reads in the table (improvements should be made to preserve the header names).

It then quickly plots the first years of data (2025, 2030, 2040) (improvements can be made to use dot indexing rather than hard-coded column numbers).

Then it applies a random color map to each axes containing a different color for each sector. Improvements should be made here because random colors may not produce visually distinctive colors.

T = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/626403/emissions_sectors2.xlsx');

Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.

fig = figure();

fig.Position(3:4) = [755,420];

tiledlayout(1,3)

ax1 = nexttile;

b1 = bar(T{:,2:4}','stacked');

ax2 = nexttile;

b2 = bar(T{:,5:7}','stacked');

ax3 = nexttile;

b3 = bar(T{:,8:10}','stacked');

rng(386)

cmap = rand(height(T),3);

set([ax1, ax2, ax3], 'ColorOrder', cmap)

legHandles = [b1 b2 b3];

lg = legend(legHandles,T.Sector,'Orientation','Horizontal','NumColumns',4);

Warning: Ignoring extra legend entries.

lg.Layout.Tile = 'North';

Plot stacked bar chart with legends (18)

Your data has a lot of missing values (NaNs in matlab.! Those values will naturally not appear in the stacked bars. Notice that the first vlaue of H2 in 2025 is NRMM which is peach-ish colored in the legend. This is also the first color that appears in bar #2 in plot 1.

Plot stacked bar chart with legends (19)

AHMED FAKHRI on 22 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536248

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1536248

Hi @Adam Danz,

To be clear, the graphs I quoted are not plotted by me, these are plotted by the orignal produced and I am trying to replicate them. Off course there will be differences in terms of the values because how they interepret electric techs or H2 techs is different to what I interepret.

The code I included just as an example of my old why which did not work of course, So I shared the Excel data instead but it was just indicative.

Many thanks for the last code, it seems this is what I want, I will check now and accept your answer, I really thanks you and apologize for the misunderstanding

Adam Danz on 23 May 2021

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1537433

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/836793-plot-stacked-bar-chart-with-legends#comment_1537433

I see. I hope you make better color choices than they did 😄.

There are a bunch of colormap functions on the file exchange that may help.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

See Also

Categories

MATLABGraphics2-D and 3-D Plots

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Tags

  • plot
  • subplot
  • legend
  • graph
  • bar

Products

  • MATLAB

Release

R2020b

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


Plot stacked bar chart with legends (22)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contact your local office

Plot stacked bar chart with legends (2024)
Top Articles
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 5689

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.