How do you make a bar graph with two sets of data in python?

Create a pandas dataframe with 3 columns crimetype, count, Season and try this function.

#Importing required packages

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

#Function Creation
def plt_grouped_bar(Plot_Nm,group_bar,x, y,plt_data,**bar_kwargs):
    plt_fig=plt.figure(figsize=(18,9))
    ax=plt_fig.add_subplot()
    g = sns.catplot(x=x, y=y, hue=group_bar,data=plt_data,ax=ax,kind="bar",**bar_kwargs)
    for p in ax.patches:
        height = p.get_height()
        ax.text(x = p.get_x()+(p.get_width()/2),
        y = height+0.05,
        s = '{:.0f}'.format(height),
        ha = 'center',va = 'bottom',zorder=20, rotation=90)
    ax.set_title(Plot_Nm,fontweight="bold",fontsize=18,alpha=0.7,y=1.03)
    g.set_xticklabels(x,fontsize=10,alpha=0.8,fontweight="bold")
    plt.setp(ax.get_xticklabels(), rotation=90)
    ax.set_yticklabels("")
    ax.set_xlabel("")
    ax.set_ylabel("")
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.tick_params(axis=u'both',length=0)
    ax.legend(loc='upper right')
    for spine in ax.spines:
        ax.spines[spine].set_visible(False)
    plt.close()

#Calling the function
plt_grouped_bar('Title of bar','weather','crimetype','count',pandasdataframename)

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    A multiple bar chart is also called a Grouped Bar chart. A Bar plot or a Bar Chart has many customizations such as Multiple bar plots, stacked bar plots, horizontal bar charts. Multiple bar charts are generally used for comparing different entities. In this article, plotting multiple bar charts are discussed.

    Example 1: Simple multiple bar chart

    In this example we will see how to plot multiple bar charts using matplotlib, here we are plotting multiple bar charts to visualize the number of boys and girls in each Group.

    Approach:

    1. Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.
    2. The data for plotting multiple bar charts are taken into the list.
    3. The np.arange( ) function from numpy library is used to create a range of values. We are creating the X-axis values depending on the number of groups in our example.
    4. Plotting the multiple bars using plt.bar( ) function.
    5. To avoid overlapping of bars in each group, the bars are shifted -0.2 units and +0.2 units from the X-axis.
    6. The width of the bars of each group is taken as 0.4 units.
    7. Finally, the multiple bar charts for both boys and girls are plotted in each group.

    Code:

    Python3

    import numpy as np 

    import matplotlib.pyplot as plt 

    X = ['Group A','Group B','Group C','Group D']

    Ygirls = [10,20,20,40]

    Zboys = [20,30,25,30]

    X_axis = np.arange(len(X))

    plt.bar(X_axis - 0.2, Ygirls, 0.4, label = 'Girls')

    plt.bar(X_axis + 0.2, Zboys, 0.4, label = 'Boys')

    plt.xticks(X_axis, X)

    plt.xlabel("Groups")

    plt.ylabel("Number of Students")

    plt.title("Number of Students in each group")

    plt.legend()

    plt.show()

    Output :

    How do you make a bar graph with two sets of data in python?

    Example 2: Number of Men and Women voted from 2018-2021

    Approach :

    1. Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.
    2. The Men and Women data for multiple bar charts are taken into a list for easy plotting.
    3. The np.arange( ) function from numpy library is used to create a range of values.
    4. Plotting the multiple bars using plt.bar( ) function in matplotlib library.
    5. To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the X-axis in this example.
    6. The width of the bars of each group is taken as 0.25 units.
    7. The X-axis labels(Years) and x-ticks are plotted as required in our visualization.
    8. Finally, the multiple bar chart for the number of men and women who voted every year is plotted.

    Code:

    Python3

    import numpy as np

    import matplotlib.pyplot as plt

    Women = [115, 215, 250, 200]

    Men = [114, 230, 510, 370]

    n=4

    r = np.arange(n)

    width = 0.25

    plt.bar(r, Women, color = 'b',

            width = width, edgecolor = 'black',

            label='Women')

    plt.bar(r + width, Men, color = 'g',

            width = width, edgecolor = 'black',

            label='Men')

    plt.xlabel("Year")

    plt.ylabel("Number of people voted")

    plt.title("Number of people voted in each year")

    plt.xticks(r + width/2,['2018','2019','2020','2021'])

    plt.legend()

    plt.show()

    Output :

    How do you make a bar graph with two sets of data in python?

    Example3: Scores of different players on different dates

    Approach:

    1. Importing required libraries such as numpy for performing numerical calculations with arrays and matplotlib for visualization of data.
    2. The np.arange( ) function from numpy library is used to create a range of values(Here, 3 values).
    3. Plotting the multiple bars using plt.bar( ) function in matplotlib library. In this Example, Dates are plotted on X-axis and Players Scores on Y-axis.
    4. To avoid overlapping of bars in each group, the bars are shifted 0.25 units from the previous bar.
    5. The width of the bars of each group is taken as 0.25 units with different colors.
    6. The X-axis labels and x-ticks are plotted as required in our visualization.
    7. Finally, the multiple bar chart for the Scores of different players on different dates is plotted.

    Code:

    Python3

    import numpy as np

    import matplotlib.pyplot as plt

    N = 3

    ind = np.arange(N) 

    width = 0.25

    xvals = [8, 9, 2]

    bar1 = plt.bar(ind, xvals, width, color = 'r')

    yvals = [10, 20, 30]

    bar2 = plt.bar(ind+width, yvals, width, color='g')

    zvals = [11, 12, 13]

    bar3 = plt.bar(ind+width*2, zvals, width, color = 'b')

    plt.xlabel("Dates")

    plt.ylabel('Scores')

    plt.title("Players Score")

    plt.xticks(ind+width,['2021Feb01', '2021Feb02', '2021Feb03'])

    plt.legend( (bar1, bar2, bar3), ('Player1', 'Player2', 'Player3') )

    plt.show()

    Output:

    How do you make a bar graph with two sets of data in python?


    How do you make a double bar graph in Python?

    Matplotlib multiple horizontal bar chart.
    y: specify coordinates of the y bars..
    width: specify the width of the bars..
    height: specify the height of the bars..
    left: specify the x coordinates of the left sides of the bars..
    align: alignment of the base to the y coordinates..

    How do you plot two values in a graph in Python?

    Following steps were followed:.
    Define the x-axis and corresponding y-axis values as lists..
    Plot them on canvas using . plot() function..
    Give a name to x-axis and y-axis using . xlabel() and . ylabel() functions..
    Give a title to your plot using . title() function..
    Finally, to view your plot, we use . show() function..