Diverging Bar Chart using Python Last Updated : 23 May, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report Diverging Bar Charts are used to ease the comparison of multiple groups. Its design allows us to compare numerical values in various groups. It also helps us to quickly visualize the favorable and unfavorable or positive and negative responses. The bar chart consisted of a combination of two horizontal bars starting from the middle- one bar extends out from right to left and the other extends out from left to right. The length of the bar is corresponding to the numerical value it represents. Commonly the two diverging bars are represented with different colors. Values to the left are usually but not necessarily negative or unsatisfactory responses. Python doesn't have a particular function to plot diverging bar charts. The alternate way is to use hlines function to draw horizontal lines with a certain value of linewidth to represent them as horizontal bars. Datasets in use: Mercedes Benz Car Sales DataTwitter Airline SentimentMethod 1: Using Matplotlib Approach : Import moduleImport or create dataPreprocess the dataset and clean out the unnecessary noiseSpecify the colors for representing the horizontal barsSort the values in ascending orderSet the labels for the x-axis and y-axis as well as the title of the chartDisplay the Diverging Bar Chart Example 1: Python import pandas as pd import matplotlib.pyplot as plt import string as str # Creating a DataFrame from the CSV Dataset df = pd.read_csv("car_sales.csv", sep=';') # Separating the Date and Mercedes-Benz Cars unit sales (USA) df['car_sales_z'] = df.loc[:, ['Mercedes-Benz Cars unit sales (USA)']] df['car_sales_z'] = df['car_sales_z'] .str.replace( ',', '').astype(float) # Removing null value df.drop(df.tail(1).index, inplace=True) for i in range(35): # Colour of bar chart is set to red if the sales # is < 60000 and green otherwise df['colors'] = ['red' if float( x) < 60000 else 'green' for x in df['car_sales_z']] # Sort values from lowest to highest df.sort_values('car_sales_z', inplace=True) # Resets initial index in Dataframe to None df.reset_index(inplace=True) # Draw plot plt.figure(figsize=(14, 10), dpi=80) # Plotting the horizontal lines plt.hlines(y=df.index, xmin=60000, xmax=df.car_sales_z, color=df.colors, alpha=0.4, linewidth=5) # Decorations # Setting the labels of x-axis and y-axis plt.gca().set(ylabel='Quarter', xlabel='Sales') # Setting Date to y-axis plt.yticks(df.index, df.Date, fontsize=12) # Title of Bar Chart plt.title('Diverging Bars Chart Example', fontdict={ 'size': 20}) # Optional grid layout plt.grid(linestyle='--', alpha=0.5) # Displaying the Diverging Bar Chart plt.show() Output: Method 2: Using Plotly Approach: Import required librariesCreate or import dataPreprocess the Dataset and clean out the unnecessary noisePlot the graph using plotly.graph_objectsSet the labels for the x-axis and y-axis as well as the legendDisplay the Diverging Bar Chart Example: Python import pandas as pd import plotly.graph_objects as go df = pd.read_csv("Tweets.csv") df.head() # Preprocessing the dataset to extract only # the necessary columns categories = [ 'negative', 'neutral', 'positive' ] # Construct a pivot table with the column # 'airline' as the index and the sentiments # as the columns gfg = pd.pivot_table( df, index='airline', columns='airline_sentiment', values='tweet_id', aggfunc='count' ) # Include the sentiments - negative, neutral # and positive gfg = gfg[categories] # Representing negative sentiment with negative # numbers gfg.negative = gfg.negative * -1 df = gfg # Creating a Figure Diverging = go.Figure() # Iterating over the columns for col in df.columns[4:]: # Adding a trace and specifying the parameters # for negative sentiment Diverging.add_trace(go.Bar(x=-df[col].values, y=df.index, orientation='h', name=col, customdata=df[col], hovertemplate="%{y}: %{customdata}")) for col in df.columns: # Adding a trace and specifying the parameters # for positive and neutral sentiment Diverging.add_trace(go.Bar(x=df[col], y=df.index, orientation='h', name=col, hovertemplate="%{y}: %{x}")) # Specifying the layout of the plot Diverging.update_layout(barmode='relative', height=400, width=700, yaxis_autorange='reversed', bargap=0.5, legend_orientation='v', legend_x=1, legend_y=0 ) Diverging Output: Comment More infoAdvertise with us Next Article Python | Bar Charts in Vincent D deepthimgs Follow Improve Article Tags : Python Python-matplotlib Data Visualization Python-Plotly Practice Tags : python Similar Reads Diverging Bar Chart in R Diverging Bar Chart is a kind of bar chart which are mostly used to compare two or more variables that are plotted on different sides of the middle bar. In diverging bar plot, the positive charts are plotted on the right side of the diverging(middle) axis and negative values are placed on the other 4 min read Bar chart using Plotly in Python Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization librar 4 min read Python | Bar Charts in Vincent In this article, we will create bar charts with the help for vincent. Which is a library in python which does python to vega translation? It has the data capabilities of python and the visualization capabilities of javascript. It is built specifically for plotting Dataframes and series quickly. Requ 1 min read Create Grouped Bar Chart using Altair in Python Grouped bar charts are a handy tool to represent our data when we want to compare multiple sets of data items one against another. To make a grouped bar chart, we require at least three rows of three columns of data in our dataset. The three columns can be used as- one for values, one for series, an 3 min read Bar chart with Altair in Python Altair is a declarative statistical visualization library for Python, built on top of the Vega-Lite visualization grammar. It provides a simple and intuitive API for creating a wide range of interactive and informative visualizations, including bar charts. This article will guide you through the pro 2 min read Python | Basic Gantt chart using Matplotlib Prerequisites : Matplotlib IntroductionIn this article, we will be discussing how to plot a Gantt Chart in Python using Matplotlib.A Gantt chart is a graphical depiction of a project schedule or task schedule (In OS). It's is a type of bar chart that shows the start and finish dates of several eleme 3 min read Like