Diverging Bar Chart using Python

Diverging Bar Chart using Python

A diverging bar chart is useful when you want to visualize the variation, particularly variance, of data points from a particular baseline, usually zero. This type of chart helps in highlighting values that are above and below a specific reference point.

Here's how you can create a diverging bar chart using Python with the help of the matplotlib and pandas libraries:

  1. Setup

    Firstly, make sure to install the necessary libraries:

    pip install matplotlib pandas 
  2. Example

    Let's say we have a dataset showing the deviation of scores from the average score:

    import pandas as pd import matplotlib.pyplot as plt # Sample data data = { 'Students': ['John', 'Lila', 'Sam', 'Anna', 'Edward', 'Christina', 'George'], 'Score Deviation': [10, -15, 7, -3, 12, -8, 5] } df = pd.DataFrame(data) # Sorting data to make the chart more intuitive df = df.sort_values(by='Score Deviation') # Plotting plt.figure(figsize=(10, 6)) bars = plt.barh(df['Students'], df['Score Deviation'], color=(df['Score Deviation'] > 0).map({True: 'g', False: 'r'})) plt.xlabel('Score Deviation from Average') plt.title('Diverging Bar Chart of Student Score Deviation') plt.grid(axis='x') # Display the chart plt.show() 

In the example above:

  • We created a sample dataset using pandas.

  • The dataset was sorted by 'Score Deviation' to make the chart look more organized.

  • The color argument in plt.barh() is conditionally set based on positive or negative deviation. Green ('g') bars represent positive deviations, while red ('r') bars indicate negative deviations.

  • A horizontal bar chart is plotted using barh function of matplotlib.

Run the above code, and you will get a diverging bar chart illustrating the deviation of scores for different students from an average score.


More Tags

jelly amazon-s3 laravel-4 qfiledialog dynamics-crm-2016 getattribute django-templates exceljs auth0 crashlytics

More Programming Guides

Other Guides

More Programming Examples