Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Frank Corso
Frank Corso

Posted on • Originally published atfrankcorso.dev

Creating Your First Chart Using Seaborn

When working with data in Python, there are many times when you will need to analyze or visualize the data. For example, maybe you are quickly looking for outliers or are creating a few charts to be shared.

There are many libraries for creating graphs. The most common is matplotlib. However, that can be a lot lower level than you need most of the time and has a steep learning curve.

This is where seaborn comes in.Seaborn is a library built on top of matplotlib and makes creating charts from data sets simple.

Seaborn Basics

Seaborn is tightly integrated with Pandas, so you can pass almost any data frame as the data set. Additionally, you can use a variety of other data structures too. Let’s take a look at the minimum steps for using Seaborn.

When creating a chart with Seaborn, there are only a few required steps as shown in the code below.

# Import Seaborn, usually aliased as sns.importseabornassns# Create a sample dictionary of x,y values.data={'a':1,'b':2,'c':3,'d':4}# Create a basic line chart.sns.lineplot(data=data)
Enter fullscreen modeExit fullscreen mode

This will create a line chart using all the default options assuming the dictionary pairs are x, y values, as shown in the screenshot below.

A basic line graph with no labels or title. Shows an upward line along values of a, b, c, and d.

Seaborn includes a variety of methods for built-in chart types, includinglineplot,countplot,relplot, andboxplot. You can view all of the available methodsin the Seaborn API reference.

Creating a Line Chart Using Pandas Dataframes

In many cases, you will start with a Pandas data frame with multiple columns. In this case, it will work almost the same, except we can pass the x and y names.

Let’s start with a basic dataframe that contains a few rows for the total revenue a store earned per day. We can then pass that dataframe to seaborn as we did before, but this time, we will specify the x and y axes.

# Import Pandas and Seabornimportpandasaspdimportseabornassns# Create our dataframe.df=pd.read_csv('example-df.csv')# Create a basic line chart.sns.lineplot(data=df,x='date',y='total_revenue')
Enter fullscreen modeExit fullscreen mode

Improving Your Chart

While the default graphs might work for just quickly visualizing a data set, you will often need to share these charts. With Seaborn, you have many ways to alter a chart, such as using a Seaborn helper method or using a matplotlib function on the return chart instance.

Adding Labels

First, let’s add the title. To do this, we can chain theset method directly on the chart call.

sns.lineplot(data=df,x='date',y='total_revenue').set(title='Our revenue continues to rise')
Enter fullscreen modeExit fullscreen mode

We can also use this to set the axis labels by setting thexlabel andylabel values.

sns.lineplot(data=df,x='date',y='total_revenue').set(title='Our revenue continues to rise',xlabel='',ylabel='')
Enter fullscreen modeExit fullscreen mode

This works well if we are just adding some text to the chart. But, what if we want to adjust size or positioning? We could use global Seaborn values, such as font scale, to alter all font sizes.

sns.set(font_scale=2)
Enter fullscreen modeExit fullscreen mode

However, you will often need to adjust specific labels or titles. To do this, we can access the underlying matplotlib values as shown in this code:

# Import matplotlib so we can use the plot methods.importmatplotlib.pyplotasplt# Add title and axis labelsplt.title('Our revenue continues to rise',fontsize=18)plt.xlabel('Day',fontsize=12)plt.ylabel('Revenue',fontsize=12)
Enter fullscreen modeExit fullscreen mode

Once we start using the matplotlib methods, we have a little more control over our text as well. For example, for the title, it might be better to left-align it which, we can do by using theloc parameter:

plt.title('Our revenue continues to rise',fontsize=18,loc='left')
Enter fullscreen modeExit fullscreen mode

If we need to, we can also adjust the font size of the tick labels (the labels along each axis) using a similar method:

plt.tick_params(axis='both',labelsize=8)
Enter fullscreen modeExit fullscreen mode

This gets our graph to look like this:

A line graph showing that revenue is increasing. Includes a title and labels.

Adjusting Styles

Now that we have some labels in place, we should start adjusting the graph itself. The first thing we may want to do is adjust our starting values along one or both axes. We can do this by calling matplotlib'sylim method. If we needed to, there is also axlim method.

# Set the y axis to start at 0.plt.ylim(bottom=0)
Enter fullscreen modeExit fullscreen mode

Seaborn also comes with a variety of default themes and styles as well as methods to help us control different aspects of the graph. You can start with setting theset_style method to one of five themes: darkgrid, whitegrid, dark, white, and ticks.

I normally start withwhite which we can set with this code before we start creating our charts:

sns.set_style('white')
Enter fullscreen modeExit fullscreen mode

From there, I sometimes remove the border not along the labeled axes. Seaborn has a method that takes care of this for us:

sns.despine()
Enter fullscreen modeExit fullscreen mode

Thedespine method can also accept values for specific sides and offsets. I usually start with the defaults and then fine-tune, if needed.

So, if we use these with our graph, our code looks like this:

importmatplotlib.pyplotaspltimportpandasaspdimportseabornassns# Create our dataframe.df=pd.read_csv('example-df.csv')# Set the default theme.sns.set_style('white')# Create our chart.sns.lineplot(data=df,x='date',y='total_revenue')# Add our text.plt.title('Our revenue continues to rise',fontsize=18,loc='left')plt.xlabel('Day',fontsize=12)plt.ylabel('Revenue',fontsize=12)plt.tick_params(axis='both',labelsize=8)# Set the y axis to start at 0.plt.ylim(bottom=0)# Remove extra borders.sns.despine()
Enter fullscreen modeExit fullscreen mode

This results in a graph like the following image.

Same graph as above but looking a little cleaner.

While there is a lot more we could do with this graph using Seaborn's functionality, this is already a chart that can be used in your analysis or sharing with colleagues. Great job learning the basics of Seaborn!

Next Steps

Now that you know how to create a basic graph using Seaborn, go ahead and try to create a few charts. From there, you will want to try adjusting the styling more as well as creating other chart types. Here are a few ideas to get you started:

  1. Try to change the color of the title to a color that matches a brand you like.
  2. Try to change the color and width of the line.
  3. Try creating a bar graph using Seaborn.

Be sure to follow to get notified when my next article is published!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Data Lover | Indie Software Founder | Full-Stack Developer
  • Location
    Gainesville, FL
  • Work
    Building https://litesurveys.com
  • Joined

More fromFrank Corso

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp