Matplotlib plot multiple bars in one graph





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have a plot with multiple bars with different scenarios, but when I plot it all the bars are repeated. Please find below my code.



I know that I'm using only one value at a time from the list, but when I try to pass the whole sub-array using data[0] instead, I get a Value mismatch error:



ValueError: shape mismatch: objects cannot be broadcast to a single shape



What am I doing wrong? I looked at the PyPlot example and this other post and both pass an array to ax.bar.



import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = [[20, 35, 30, 40], [25, 40, 45, 30],
[15, 20, 35, 45], [10, 25, 40, 15],
[50, 20, 45, 55], [10, 55, 60, 20]]
data_std = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[0][0], width, color='#000080', label='Case-1', yerr=data_std[0][0])
ax.bar(x + width, data[0][1], width, color='#0F52BA', label='Case-2', yerr=data_std[0][1])
ax.bar(x + (2 * width), data[0][2], width, color='#6593F5', label='Case-3', yerr=data_std[0][2])
ax.bar(x + (3 * width), data[0][3], width, color='#73C2FB', label='Case-4', yerr=data_std[0][3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()


Result is:



Plot using one value










share|improve this question

























  • What would be the expected outcome when you "pass the whole sub-array using data[0] instead"? This does not seem to make much sense, so maybe you want to explain what you would like to see your plot to look like?

    – ImportanceOfBeingErnest
    Nov 16 '18 at 16:56











  • @ImportanceOfBeingErnest I updated the post with the current plot. As you can see, all the bars are the same for every scenario. I'd like to change the code to plot the other values as well

    – user9518022
    Nov 16 '18 at 17:00


















0















I have a plot with multiple bars with different scenarios, but when I plot it all the bars are repeated. Please find below my code.



I know that I'm using only one value at a time from the list, but when I try to pass the whole sub-array using data[0] instead, I get a Value mismatch error:



ValueError: shape mismatch: objects cannot be broadcast to a single shape



What am I doing wrong? I looked at the PyPlot example and this other post and both pass an array to ax.bar.



import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = [[20, 35, 30, 40], [25, 40, 45, 30],
[15, 20, 35, 45], [10, 25, 40, 15],
[50, 20, 45, 55], [10, 55, 60, 20]]
data_std = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[0][0], width, color='#000080', label='Case-1', yerr=data_std[0][0])
ax.bar(x + width, data[0][1], width, color='#0F52BA', label='Case-2', yerr=data_std[0][1])
ax.bar(x + (2 * width), data[0][2], width, color='#6593F5', label='Case-3', yerr=data_std[0][2])
ax.bar(x + (3 * width), data[0][3], width, color='#73C2FB', label='Case-4', yerr=data_std[0][3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()


Result is:



Plot using one value










share|improve this question

























  • What would be the expected outcome when you "pass the whole sub-array using data[0] instead"? This does not seem to make much sense, so maybe you want to explain what you would like to see your plot to look like?

    – ImportanceOfBeingErnest
    Nov 16 '18 at 16:56











  • @ImportanceOfBeingErnest I updated the post with the current plot. As you can see, all the bars are the same for every scenario. I'd like to change the code to plot the other values as well

    – user9518022
    Nov 16 '18 at 17:00














0












0








0








I have a plot with multiple bars with different scenarios, but when I plot it all the bars are repeated. Please find below my code.



I know that I'm using only one value at a time from the list, but when I try to pass the whole sub-array using data[0] instead, I get a Value mismatch error:



ValueError: shape mismatch: objects cannot be broadcast to a single shape



What am I doing wrong? I looked at the PyPlot example and this other post and both pass an array to ax.bar.



import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = [[20, 35, 30, 40], [25, 40, 45, 30],
[15, 20, 35, 45], [10, 25, 40, 15],
[50, 20, 45, 55], [10, 55, 60, 20]]
data_std = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[0][0], width, color='#000080', label='Case-1', yerr=data_std[0][0])
ax.bar(x + width, data[0][1], width, color='#0F52BA', label='Case-2', yerr=data_std[0][1])
ax.bar(x + (2 * width), data[0][2], width, color='#6593F5', label='Case-3', yerr=data_std[0][2])
ax.bar(x + (3 * width), data[0][3], width, color='#73C2FB', label='Case-4', yerr=data_std[0][3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()


Result is:



Plot using one value










share|improve this question
















I have a plot with multiple bars with different scenarios, but when I plot it all the bars are repeated. Please find below my code.



I know that I'm using only one value at a time from the list, but when I try to pass the whole sub-array using data[0] instead, I get a Value mismatch error:



ValueError: shape mismatch: objects cannot be broadcast to a single shape



What am I doing wrong? I looked at the PyPlot example and this other post and both pass an array to ax.bar.



import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = [[20, 35, 30, 40], [25, 40, 45, 30],
[15, 20, 35, 45], [10, 25, 40, 15],
[50, 20, 45, 55], [10, 55, 60, 20]]
data_std = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[0][0], width, color='#000080', label='Case-1', yerr=data_std[0][0])
ax.bar(x + width, data[0][1], width, color='#0F52BA', label='Case-2', yerr=data_std[0][1])
ax.bar(x + (2 * width), data[0][2], width, color='#6593F5', label='Case-3', yerr=data_std[0][2])
ax.bar(x + (3 * width), data[0][3], width, color='#73C2FB', label='Case-4', yerr=data_std[0][3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()


Result is:



Plot using one value







python matplotlib






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 16:59

























asked Nov 16 '18 at 16:49







user9518022




















  • What would be the expected outcome when you "pass the whole sub-array using data[0] instead"? This does not seem to make much sense, so maybe you want to explain what you would like to see your plot to look like?

    – ImportanceOfBeingErnest
    Nov 16 '18 at 16:56











  • @ImportanceOfBeingErnest I updated the post with the current plot. As you can see, all the bars are the same for every scenario. I'd like to change the code to plot the other values as well

    – user9518022
    Nov 16 '18 at 17:00



















  • What would be the expected outcome when you "pass the whole sub-array using data[0] instead"? This does not seem to make much sense, so maybe you want to explain what you would like to see your plot to look like?

    – ImportanceOfBeingErnest
    Nov 16 '18 at 16:56











  • @ImportanceOfBeingErnest I updated the post with the current plot. As you can see, all the bars are the same for every scenario. I'd like to change the code to plot the other values as well

    – user9518022
    Nov 16 '18 at 17:00

















What would be the expected outcome when you "pass the whole sub-array using data[0] instead"? This does not seem to make much sense, so maybe you want to explain what you would like to see your plot to look like?

– ImportanceOfBeingErnest
Nov 16 '18 at 16:56





What would be the expected outcome when you "pass the whole sub-array using data[0] instead"? This does not seem to make much sense, so maybe you want to explain what you would like to see your plot to look like?

– ImportanceOfBeingErnest
Nov 16 '18 at 16:56













@ImportanceOfBeingErnest I updated the post with the current plot. As you can see, all the bars are the same for every scenario. I'd like to change the code to plot the other values as well

– user9518022
Nov 16 '18 at 17:00





@ImportanceOfBeingErnest I updated the post with the current plot. As you can see, all the bars are the same for every scenario. I'd like to change the code to plot the other values as well

– user9518022
Nov 16 '18 at 17:00












1 Answer
1






active

oldest

votes


















1














You want to plot the data column-wise. Hence it makes sense to convert the lists to arrays and select the respective column to plot.



import numpy as np
import matplotlib.pyplot as plt

data = np.array([[20, 35, 30, 40], [25, 40, 45, 30],
[15, 20, 35, 45], [10, 25, 40, 15],
[50, 20, 45, 55], [10, 55, 60, 20]])
data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()


enter image description here






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342170%2fmatplotlib-plot-multiple-bars-in-one-graph%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown
























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You want to plot the data column-wise. Hence it makes sense to convert the lists to arrays and select the respective column to plot.



    import numpy as np
    import matplotlib.pyplot as plt

    data = np.array([[20, 35, 30, 40], [25, 40, 45, 30],
    [15, 20, 35, 45], [10, 25, 40, 15],
    [50, 20, 45, 55], [10, 55, 60, 20]])
    data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
    [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])

    length = len(data)
    x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

    # Set plot parameters
    fig, ax = plt.subplots()
    width = 0.2 # width of bar
    x = np.arange(length)

    ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
    ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
    ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
    ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

    ax.set_ylabel('Metric')
    ax.set_ylim(0,75)
    ax.set_xticks(x + width + width/2)
    ax.set_xticklabels(x_labels)
    ax.set_xlabel('Scenario')
    ax.set_title('Title')
    ax.legend()
    plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

    fig.tight_layout()
    plt.show()


    enter image description here






    share|improve this answer




























      1














      You want to plot the data column-wise. Hence it makes sense to convert the lists to arrays and select the respective column to plot.



      import numpy as np
      import matplotlib.pyplot as plt

      data = np.array([[20, 35, 30, 40], [25, 40, 45, 30],
      [15, 20, 35, 45], [10, 25, 40, 15],
      [50, 20, 45, 55], [10, 55, 60, 20]])
      data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
      [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])

      length = len(data)
      x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

      # Set plot parameters
      fig, ax = plt.subplots()
      width = 0.2 # width of bar
      x = np.arange(length)

      ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
      ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
      ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
      ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

      ax.set_ylabel('Metric')
      ax.set_ylim(0,75)
      ax.set_xticks(x + width + width/2)
      ax.set_xticklabels(x_labels)
      ax.set_xlabel('Scenario')
      ax.set_title('Title')
      ax.legend()
      plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

      fig.tight_layout()
      plt.show()


      enter image description here






      share|improve this answer


























        1












        1








        1







        You want to plot the data column-wise. Hence it makes sense to convert the lists to arrays and select the respective column to plot.



        import numpy as np
        import matplotlib.pyplot as plt

        data = np.array([[20, 35, 30, 40], [25, 40, 45, 30],
        [15, 20, 35, 45], [10, 25, 40, 15],
        [50, 20, 45, 55], [10, 55, 60, 20]])
        data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
        [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])

        length = len(data)
        x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

        # Set plot parameters
        fig, ax = plt.subplots()
        width = 0.2 # width of bar
        x = np.arange(length)

        ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
        ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
        ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
        ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

        ax.set_ylabel('Metric')
        ax.set_ylim(0,75)
        ax.set_xticks(x + width + width/2)
        ax.set_xticklabels(x_labels)
        ax.set_xlabel('Scenario')
        ax.set_title('Title')
        ax.legend()
        plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

        fig.tight_layout()
        plt.show()


        enter image description here






        share|improve this answer













        You want to plot the data column-wise. Hence it makes sense to convert the lists to arrays and select the respective column to plot.



        import numpy as np
        import matplotlib.pyplot as plt

        data = np.array([[20, 35, 30, 40], [25, 40, 45, 30],
        [15, 20, 35, 45], [10, 25, 40, 15],
        [50, 20, 45, 55], [10, 55, 60, 20]])
        data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2],
        [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])

        length = len(data)
        x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

        # Set plot parameters
        fig, ax = plt.subplots()
        width = 0.2 # width of bar
        x = np.arange(length)

        ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
        ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
        ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
        ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

        ax.set_ylabel('Metric')
        ax.set_ylim(0,75)
        ax.set_xticks(x + width + width/2)
        ax.set_xticklabels(x_labels)
        ax.set_xlabel('Scenario')
        ax.set_title('Title')
        ax.legend()
        plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

        fig.tight_layout()
        plt.show()


        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 17:07









        ImportanceOfBeingErnestImportanceOfBeingErnest

        142k13169248




        142k13169248
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342170%2fmatplotlib-plot-multiple-bars-in-one-graph%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues