Python Create Bar Chart Comparing 2 sets of data











up vote
2
down vote

favorite
1












I have a notebook with 2* bar charts, one is winter data & one is summer data. I have counted the total of all the crimes and plotted them in a bar chart, using code:



ax = summer["crime_type"].value_counts().plot(kind='bar')
plt.show()


Which shows a graph like:



enter image description here



I have another chart nearly identical, but for winter:



ax = winter["crime_type"].value_counts().plot(kind='bar')
plt.show()


And I would like to have these 2 charts compared against one another in the same bar chart (Where every crime on the x axis has 2 bars coming from it, one winter & one summer).



I have tried, which is just me experimenting:



bx = (summer["crime_type"],winter["crime_type"]).value_counts().plot(kind='bar')
plt.show()


Any advice would be appreciated!










share|improve this question









New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Hi there, sounds like you need a grouped bar chart. Please post some sample data so people can experiment. Also, post the Python package you need to use - matplotlib, pandas, etc. If you can combine summer and winter data together, then there are examples of this with matplotlib (1, 2) or pandas plotting. If they must be kept separate, see 1
    – W R
    2 days ago

















up vote
2
down vote

favorite
1












I have a notebook with 2* bar charts, one is winter data & one is summer data. I have counted the total of all the crimes and plotted them in a bar chart, using code:



ax = summer["crime_type"].value_counts().plot(kind='bar')
plt.show()


Which shows a graph like:



enter image description here



I have another chart nearly identical, but for winter:



ax = winter["crime_type"].value_counts().plot(kind='bar')
plt.show()


And I would like to have these 2 charts compared against one another in the same bar chart (Where every crime on the x axis has 2 bars coming from it, one winter & one summer).



I have tried, which is just me experimenting:



bx = (summer["crime_type"],winter["crime_type"]).value_counts().plot(kind='bar')
plt.show()


Any advice would be appreciated!










share|improve this question









New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Hi there, sounds like you need a grouped bar chart. Please post some sample data so people can experiment. Also, post the Python package you need to use - matplotlib, pandas, etc. If you can combine summer and winter data together, then there are examples of this with matplotlib (1, 2) or pandas plotting. If they must be kept separate, see 1
    – W R
    2 days ago















up vote
2
down vote

favorite
1









up vote
2
down vote

favorite
1






1





I have a notebook with 2* bar charts, one is winter data & one is summer data. I have counted the total of all the crimes and plotted them in a bar chart, using code:



ax = summer["crime_type"].value_counts().plot(kind='bar')
plt.show()


Which shows a graph like:



enter image description here



I have another chart nearly identical, but for winter:



ax = winter["crime_type"].value_counts().plot(kind='bar')
plt.show()


And I would like to have these 2 charts compared against one another in the same bar chart (Where every crime on the x axis has 2 bars coming from it, one winter & one summer).



I have tried, which is just me experimenting:



bx = (summer["crime_type"],winter["crime_type"]).value_counts().plot(kind='bar')
plt.show()


Any advice would be appreciated!










share|improve this question









New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I have a notebook with 2* bar charts, one is winter data & one is summer data. I have counted the total of all the crimes and plotted them in a bar chart, using code:



ax = summer["crime_type"].value_counts().plot(kind='bar')
plt.show()


Which shows a graph like:



enter image description here



I have another chart nearly identical, but for winter:



ax = winter["crime_type"].value_counts().plot(kind='bar')
plt.show()


And I would like to have these 2 charts compared against one another in the same bar chart (Where every crime on the x axis has 2 bars coming from it, one winter & one summer).



I have tried, which is just me experimenting:



bx = (summer["crime_type"],winter["crime_type"]).value_counts().plot(kind='bar')
plt.show()


Any advice would be appreciated!







python pandas bar-chart






share|improve this question









New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 2 days ago





















New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









A Johnston

164




164




New contributor




A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






A Johnston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Hi there, sounds like you need a grouped bar chart. Please post some sample data so people can experiment. Also, post the Python package you need to use - matplotlib, pandas, etc. If you can combine summer and winter data together, then there are examples of this with matplotlib (1, 2) or pandas plotting. If they must be kept separate, see 1
    – W R
    2 days ago




















  • Hi there, sounds like you need a grouped bar chart. Please post some sample data so people can experiment. Also, post the Python package you need to use - matplotlib, pandas, etc. If you can combine summer and winter data together, then there are examples of this with matplotlib (1, 2) or pandas plotting. If they must be kept separate, see 1
    – W R
    2 days ago


















Hi there, sounds like you need a grouped bar chart. Please post some sample data so people can experiment. Also, post the Python package you need to use - matplotlib, pandas, etc. If you can combine summer and winter data together, then there are examples of this with matplotlib (1, 2) or pandas plotting. If they must be kept separate, see 1
– W R
2 days ago






Hi there, sounds like you need a grouped bar chart. Please post some sample data so people can experiment. Also, post the Python package you need to use - matplotlib, pandas, etc. If you can combine summer and winter data together, then there are examples of this with matplotlib (1, 2) or pandas plotting. If they must be kept separate, see 1
– W R
2 days ago














1 Answer
1






active

oldest

votes

















up vote
0
down vote













The following generates dummies of your data and does the grouped bar chart you wanted:



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

s = "Crime Type Summer|Crime Type Winter".split("|")

# Generate dummy data into a dataframe
j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
) for j in range(300)] for x in s}
df = pd.DataFrame(j)

index = np.arange(5)
bar_width = 0.35

fig, ax = plt.subplots()
summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
label="Summer")

winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
bar_width, label="Winter")

ax.set_xlabel('Category')
ax.set_ylabel('Incidence')
ax.set_title('Crime incidence by season, type')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
ax.legend()

plt.show()


With this script I got:



this image



You can check out the demo in the matplotlib docs here: https://matplotlib.org/gallery/statistics/barchart_demo.html



The important thing to note is the index!



index = np.arange(5) # Set an index of n crime types
...
summer = ax.bar(index, ...)
winter = ax.bar(index+bar_width, ...)
...
ax.set_xticks(index + bar_width / 2)


These are the lines that arrange the bars on the horizontal axis so that they are grouped together.






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',
    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
    });


    }
    });






    A Johnston is a new contributor. Be nice, and check out our Code of Conduct.










     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53182452%2fpython-create-bar-chart-comparing-2-sets-of-data%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    The following generates dummies of your data and does the grouped bar chart you wanted:



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

    s = "Crime Type Summer|Crime Type Winter".split("|")

    # Generate dummy data into a dataframe
    j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
    ) for j in range(300)] for x in s}
    df = pd.DataFrame(j)

    index = np.arange(5)
    bar_width = 0.35

    fig, ax = plt.subplots()
    summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
    label="Summer")

    winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
    bar_width, label="Winter")

    ax.set_xlabel('Category')
    ax.set_ylabel('Incidence')
    ax.set_title('Crime incidence by season, type')
    ax.set_xticks(index + bar_width / 2)
    ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
    ax.legend()

    plt.show()


    With this script I got:



    this image



    You can check out the demo in the matplotlib docs here: https://matplotlib.org/gallery/statistics/barchart_demo.html



    The important thing to note is the index!



    index = np.arange(5) # Set an index of n crime types
    ...
    summer = ax.bar(index, ...)
    winter = ax.bar(index+bar_width, ...)
    ...
    ax.set_xticks(index + bar_width / 2)


    These are the lines that arrange the bars on the horizontal axis so that they are grouped together.






    share|improve this answer

























      up vote
      0
      down vote













      The following generates dummies of your data and does the grouped bar chart you wanted:



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

      s = "Crime Type Summer|Crime Type Winter".split("|")

      # Generate dummy data into a dataframe
      j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
      ) for j in range(300)] for x in s}
      df = pd.DataFrame(j)

      index = np.arange(5)
      bar_width = 0.35

      fig, ax = plt.subplots()
      summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
      label="Summer")

      winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
      bar_width, label="Winter")

      ax.set_xlabel('Category')
      ax.set_ylabel('Incidence')
      ax.set_title('Crime incidence by season, type')
      ax.set_xticks(index + bar_width / 2)
      ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
      ax.legend()

      plt.show()


      With this script I got:



      this image



      You can check out the demo in the matplotlib docs here: https://matplotlib.org/gallery/statistics/barchart_demo.html



      The important thing to note is the index!



      index = np.arange(5) # Set an index of n crime types
      ...
      summer = ax.bar(index, ...)
      winter = ax.bar(index+bar_width, ...)
      ...
      ax.set_xticks(index + bar_width / 2)


      These are the lines that arrange the bars on the horizontal axis so that they are grouped together.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        The following generates dummies of your data and does the grouped bar chart you wanted:



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

        s = "Crime Type Summer|Crime Type Winter".split("|")

        # Generate dummy data into a dataframe
        j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
        ) for j in range(300)] for x in s}
        df = pd.DataFrame(j)

        index = np.arange(5)
        bar_width = 0.35

        fig, ax = plt.subplots()
        summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
        label="Summer")

        winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
        bar_width, label="Winter")

        ax.set_xlabel('Category')
        ax.set_ylabel('Incidence')
        ax.set_title('Crime incidence by season, type')
        ax.set_xticks(index + bar_width / 2)
        ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
        ax.legend()

        plt.show()


        With this script I got:



        this image



        You can check out the demo in the matplotlib docs here: https://matplotlib.org/gallery/statistics/barchart_demo.html



        The important thing to note is the index!



        index = np.arange(5) # Set an index of n crime types
        ...
        summer = ax.bar(index, ...)
        winter = ax.bar(index+bar_width, ...)
        ...
        ax.set_xticks(index + bar_width / 2)


        These are the lines that arrange the bars on the horizontal axis so that they are grouped together.






        share|improve this answer












        The following generates dummies of your data and does the grouped bar chart you wanted:



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

        s = "Crime Type Summer|Crime Type Winter".split("|")

        # Generate dummy data into a dataframe
        j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
        ) for j in range(300)] for x in s}
        df = pd.DataFrame(j)

        index = np.arange(5)
        bar_width = 0.35

        fig, ax = plt.subplots()
        summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
        label="Summer")

        winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
        bar_width, label="Winter")

        ax.set_xlabel('Category')
        ax.set_ylabel('Incidence')
        ax.set_title('Crime incidence by season, type')
        ax.set_xticks(index + bar_width / 2)
        ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
        ax.legend()

        plt.show()


        With this script I got:



        this image



        You can check out the demo in the matplotlib docs here: https://matplotlib.org/gallery/statistics/barchart_demo.html



        The important thing to note is the index!



        index = np.arange(5) # Set an index of n crime types
        ...
        summer = ax.bar(index, ...)
        winter = ax.bar(index+bar_width, ...)
        ...
        ax.set_xticks(index + bar_width / 2)


        These are the lines that arrange the bars on the horizontal axis so that they are grouped together.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        Charles Landau

        5069




        5069






















            A Johnston is a new contributor. Be nice, and check out our Code of Conduct.










             

            draft saved


            draft discarded


















            A Johnston is a new contributor. Be nice, and check out our Code of Conduct.













            A Johnston is a new contributor. Be nice, and check out our Code of Conduct.












            A Johnston is a new contributor. Be nice, and check out our Code of Conduct.















             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53182452%2fpython-create-bar-chart-comparing-2-sets-of-data%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            横浜市

            Rostock

            Europa