No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Bar Plot with Python and seaborn

by Khaleel O.
August 3, 2021
in Python
Reading Time: 3 mins read
A A
bar plot python seaborn
bar plot python seaborn

Let’s create a Bar Plot in Python with the seaborn library. First, let’s install the library:

pip install seaborn

Next, let’s write our sample code:

import seaborn as sns
import pandas as pd

d = {'YEARS': ['2008','2009','2010','2011','2012'], 'SALES': [20000,25000,30000,19000,35000] }

df = pd.DataFrame(data=d)
sns.set_theme(style="whitegrid", rc={'figure.figsize':(11.7,8.27)})
ax = sns.barplot(x="YEARS", y="SALES", data=df)

import matplotlib.pyplot as plt
plt.show()

Let’s explain what is going here:

  1. We import the seaborn and pandas libraries first.
  2. We define our data d and we create our dataframe df. This dataframe will have two columns: YEARS and SALES.
  3. sns.set_theme() allows us to set multiple theme parameters in one step. We are only setting the style parameter in this case which can be one of the following: darkgrid, whitegrid, dark, white, ticks. The method also accepts the rc parameter which overrides parameter mappings. In this case we are mapping the figure.figsize parameter from matplotlib which sets the width and height of the plot in inches.
  4. sns.barplot() shows the data in our dataset df as rectangular bars. Parameters x and y are our inputs. x represents the YEARS column and it will appear on the x-axis or horizontal axis of our bar plot. y represents the SALES column and it appears y-axis or vertical axis of our bar plot.
  5. Because seaborn is based on the matplotlib library we must import the same and use the plt.show() method to display our plot on the screen.

You can install matplotlib with the following command:

python -m pip install -U matplotlib

Following is the output of our code:

Fig 1: Sales vs Years

Note that we got what we expected: a bar plot with YEARS on the x-axis and SALES on the y-axis. We can improve our plot by adding the data labels above each bar with the following code:

for p in ax.patches:
    ax.annotate(f"{p.get_height()}", 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points')

The above code is simply adding our data labels neatly above each bar. A patch is a 2D figure with a face color and an edge color. In this case, a patch is a bar on our bar plot. p.height() gets the height of each bar (the same as SALES) and displays it on the top of the bar in the plot for easy visibility.✨✨ This gives us the following plot:

Fig 2: Sales Vs.Years (with Data Labels)

We hope our tutorial helped. Get the full source code HERE. And find out more about matplotlib HERE in another great tutorial.👌👌👌

Tags: bar plotmatplotlibseaborn
Previous Post

Plotly Bar Chart in Python with Code

Next Post

Python sqlite3 Create Tables

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy