Import seaborn as sns ошибка

I am trying to import seaborn into python (using 2.7) using the following code:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import math as math
from pylab import rcParams

%matplotlib inline

and getting the following error message:

ImportError                               Traceback (most recent call last)
<ipython-input-62-bd3d27f3b137> in <module>()
      1 import matplotlib.pyplot as plt
----> 2 import seaborn as sns
      3 import pandas as pd
      4 import numpy as np
      5 import math as math

C:\Python27\lib\site-packages\seaborn\__init__.py in <module>()
      2 from .utils import *
      3 from .palettes import *
----> 4 from .linearmodels import *
      5 from .distributions import *
      6 from .timeseries import *

C:\Python27\lib\site-packages\seaborn\linearmodels.py in <module>()
     19 from .external.six.moves import range
     20 
---> 21 from . import utils
     22 from . import algorithms as algo
     23 from .palettes import color_palette

ImportError: cannot import name utils

What is the cause of this error, and how can the problem be fixed?

starball's user avatar

starball

21.1k7 gold badges47 silver badges255 bronze badges

asked Mar 3, 2015 at 10:03

gincard's user avatar

8

I had faced the same problem. Restarting the notebook solved my problem.

If that doesn’t solve the problem, you can try this

pip install seaborn

Edit

As few people have posted in the comments, you can also use

python -m pip install seaborn

Plus, as per https://bugs.python.org/issue22295 it is a better way because in this case, you can specify which version of python (python3 or python2) to use for running pip

answered Nov 7, 2015 at 2:24

avp's user avatar

avpavp

2,90229 silver badges35 bronze badges

5

As @avp says the bash line pip install seaborn should work
I just had the same problem and and restarting the notebook didn’t seem to work but running the command as jupyter line magic was a neat way to fix the problem without restarting the notebook

Jupyter Code-Cell:

%%bash
pip install seaborn

answered Jan 29, 2017 at 20:01

CodingYourLife's user avatar

CodingYourLifeCodingYourLife

7,2285 gold badges55 silver badges70 bronze badges

3

I had the same problem and I am using iPython. pip or conda by itself did not work for me but when I use !conda it did work.

!conda install seaborn

answered Nov 11, 2015 at 4:48

the curious mind's user avatar

1

If your python version is 2.+, you can type below code to the terminal :

pip install seaborn

if python version is 3+, type below:

pip3 install seaborn

answered Jun 1, 2018 at 10:08

Benchur Wong's user avatar

Benchur WongBenchur Wong

2,4272 gold badges9 silver badges13 bronze badges

I have the same problem and I solved it and the explanation is as follow:

If the Seaborn package is not installed in anaconda, you will not be able to update it, namely,
if in the Terminal we type: conda update seaborn

it will fail showing:
«PackageNotFoundError: Package not found: ‘seaborn’ Package ‘seaborn’ is not installed in /Users/yifan/anaconda»

Thus we need to install seaborn in anaconda first by typing in Terminal:
conda install -c https://conda.anaconda.org/anaconda seaborn

Then the seaborn will be fetched and installed in the environment of anaconda, namely in my case, /Users/yifan/anaconda

Once this installation is done, we will be able to import seaborn in python.

Side note, to check and list all discoverable environments where python is installed in anaconda, type in Terminal:
conda info —envs

answered Dec 28, 2016 at 6:29

yifan li's user avatar

I solved this problem by looking at sys.path (the path for finding modules) while in ipython and noticed that I was in a special environment (because I use conda).

so i went to my terminal and typed «source activate py27» is my python 2.7 environment. and then «conda update seaborn», restarted my jupyter kernel, and then all was good.

answered Mar 28, 2016 at 22:44

JMann's user avatar

JMannJMann

5794 silver badges12 bronze badges

I got same issue with Seaborn.
I uninstalled python, anaconda and reinstalled anaconda 4.1.1 with python 3.6. After that installed seaboarn again

>>>conda install seaborn

And it worked. If you are still facing issue, I would recommend you doing this.

cottontail's user avatar

cottontail

11.3k18 gold badges55 silver badges54 bronze badges

answered Mar 9, 2017 at 19:47

Shikha's user avatar

I solved the same importing problem reinstalling to seaborn package with

conda install -c https://conda.anaconda.org/anaconda seaborn

by typing the command on a Windows command console Afterwards I could then import seaborn successfully when I launched the IPython Notebook via on Anaconda launcher.

On the other failed way launching the IPython Notebook via Anaconda folder did not work for me.

answered Feb 22, 2016 at 11:54

Osman Emre's user avatar

Problem may not be associated with Seaborn but Utils package which may not be installed

sudo pip uninstall requests

and reinstalling, it no longer would work at all.
Luckily, dnf install python-requests fixed the whole thing…

Also check for utils package is installed or not

You can install package using

sudo pip install utils

Check this link Python ImportError: cannot import name utils

Community's user avatar

answered Feb 3, 2017 at 9:48

Abhishek Parikh's user avatar

Abhishek ParikhAbhishek Parikh

9491 gold badge20 silver badges41 bronze badges

It seams that missing dependency of python-dev, install python-dev and then try to install seaborn, if you are using Ubuntu:

sudo apt-get install python-dev -y
pip install seaborn

answered Aug 5, 2017 at 20:29

Lin GU's user avatar

it’s a problem with the scipy package, just pip uninstall scipy and reinstall it

answered Jul 2, 2018 at 15:14

Sébastien Wieckowski's user avatar

pip install seaborn 

is also solved my problem in windows 10

answered Jul 3, 2017 at 10:01

Erkan Şirin's user avatar

Erkan ŞirinErkan Şirin

1,94519 silver badges28 bronze badges

I would definitely recommend that you install Anaconda and then use the «pip install seaborn» command from the Lab Jupyter IDE. It should work. It seems that the package is already pre-installed on Lab Jupyter.

answered Jun 26, 2019 at 12:32

Isaac Benito D.'s user avatar

  1. delete package whl file in ‘C:\Users\hp\Anaconda3\Lib\site-packages’
  2. pip uninstlal scipy and seaborn
  3. pip install scipy nd seaborn agaian

it worked for 4, win10, anaconda

answered Nov 8, 2019 at 3:20

fenny's user avatar

fennyfenny

294 bronze badges

upgrade(!) the seaborn module

python -m pip install --upgrade seaborn

answered Oct 12, 2022 at 14:43

Piotr Rząsa's user avatar

I had this problem, I was using a conda environment, and did a pip install, so i did

python3 -m pip uninstall seaborn

and then instaled it using conda with

conda install -c anaconda seaborn

solved the error for me, hope it helps

answered May 27 at 16:21

Henrique Krever's user avatar

  1. Maybe you can update the Seaborn version you installed.

Using the command

pip install --upgrade seaborn
  1. Check the dependencies to make sure they are compatible versions of Matplotlib and other dependencies required by Seaborn.

  2. Try restarting the kernel if you’re using Jupyter Notebook or another interactive Python environment.

If you have any issues, feel free to ask.

answered May 27 at 16:34

Harshavardhan's user avatar

You can try using Seaborn. It works for both 2.7 as well as 3.6. You can install it by running:

pip install seaborn

Justin Pearce's user avatar

answered May 9, 2018 at 15:34

Thanooj Ks's user avatar

Thanooj KsThanooj Ks

651 silver badge1 bronze badge

Today’s tutorial is dedicated to solving import errors related to the Seaborn data visualization module.

Module not found errors are typically ubiquitous when starting to work with a new Python library (think Pandas, numpy, requests, Matplotlib and others) in your development environment, or when you are installing a new environment from scratch either manually or using a predefined distribution like Anaconda.

Solving the Seaborn module not found error

Why is Seaborn not working in Jupyter or other data Visualization environments? The typical reason for this error is that the Seaborn package is simply not installed in your environment. Use conda or the pip Package Manager to install Seaborn and then import it into your Python development environment such as Jupyter and VSCode.

Seaborn not found error messages in Jupyter and Spyder

Below you can find a screenshot of the error message that you will get in Jupyter Notebook / Labs.

And in Spyder:

You’ll encounter similar errors in PyCharm or other Python Integrated Development Environments. In this post we’ll show how to add Seaborn to Jupyter and other IDEs.

Fix Seaborn import errors in Anaconda or MiniConda

If you are using the Anaconda or MiniConda distributions ,proceed as following:

  • Save your work.
  • Close your Jupyter notebook / Dev environment.
  • Open your Anaconda Command Prompt.
  • Type: conda activate <full os path to your Conda environment>. For example:
conda activate c:\envs\Python395
  • Hit Enter.
  • Then type pip install seaborn
  • The seaborn package will be collected from the Python package repository by the Python Package installer (pip) and installed in your operating system.
  • Once successfully installed you’ll receive a message in your Mini-Conda prompt.
  • Type Exit and hit Enter to exit the Miniconda prompt.
  • Reopen your Notebook or Python Development editor and import Seaborn, by typing:
import seaborn as sns

Note for Anaconda users: You can use the Anaconda Environment Manager to fix import errors. Anaconda provides a very intuitive graphical user interface to maintain your environment, including package installation and removal.

Pip install Seaborn to fix module not found errors in Jupyter

If you are using a standalone installation or virtual environments that you have manually configured using pip, you can use your operating system command prompt / terminal directly:

  • Save your work.
  • Exit your Jupyter Notebook or IDE.
  • Open the Windows command prompt (cmd).
  • In Windows type cd <full_path to your Python environment> – for example:
cd c:\My_Python_Env
  • Then type:
pip install seaborn
  • Hit Enter.
  • After Seaborn is installed, type exit and hit Enter.
  • Reopen your notebook and import Seaborn by typing:
import seaborn as sns

Note: in case that the above instructions didn’t solve your SNS not found error message, make sure to close Jupyter or your Python IDE (VSCode, Spyder) and start it again. If this doesn’t help save your work and restart your computer.

Finding installed packages in your Development Environment

Before starting troubleshooting any issues related to third party Python packages, you might want to use the command pip list to find out which packages are installed in your system.

Proceed as following:

  • Open the command prompt or Anaconda Prompt
  • If using Anaconda, activate your environment.
  • Type the following command
pip list

    The list of 3rd party packages in your environment will be displayed:

    Happy data visualization 🙂

    A common error you may encounter when using Python is modulenotfounderror: no module named ‘seaborn’.

    This error occurs if you do not install seaborn before importing it or install it in the wrong environment.

    You can install seaborn in Python 3 with python3 -m pip install seaborn.

    This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.


    Table of contents

    • What is ModuleNotFoundError?
      • What is seaborn?
    • Always Use a Virtual Environment to Install Packages
      • How to Install seaborn on Windows Operating System
      • How to Install seaborn on Mac Operating System using pip
      • How to Install seaborn on Linux Operating Systems
        • Installing pip for Ubuntu, Debian, and Linux Mint
        • Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
        • Installing pip for CentOS 6 and 7, and older versions of Red Hat
        • Installing pip for Arch Linux and Manjaro
        • Installing pip for OpenSUSE
        • seaborn installation on Linux with Pip
    • Installing seaborn Using Anaconda
      • Check seaborn Version
    • Using seaborn Example
    • Summary

    What is ModuleNotFoundError?

    The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:

    The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:

    import ree
    ---------------------------------------------------------------------------
    ModuleNotFoundError                       Traceback (most recent call last)
    1 import ree
    
    ModuleNotFoundError: No module named 'ree'

    To solve this error, ensure the module name is correct. Let’s look at the revised code:

    import re
    
    print(re.__version__)
    2.2.1

    You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:

    mkdir example_package
    
    cd example_package
    
    mkdir folder_1
    
    cd folder_1
    
    vi module.py

    Note that we use Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:

    import re
    
    def print_re_version():
    
        print(re.__version__)

    Close the module.py, then complete the following commands from your terminal:

    cd ../
    
    vi script.py

    Inside script.py, we will try to import the module we created.

    import module
    
    if __name__ == '__main__':
    
        mod.print_re_version()

    Let’s run python script.py from the terminal to see what happens:

    Traceback (most recent call last):
      File "script.py", line 1, in ≺module≻
        import module
    ModuleNotFoundError: No module named 'module'

    To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:

    import folder_1.module as mod
    
    if __name__ == '__main__':
    
        mod.print_re_version()

    When we run python script.py, we will get the following result:

    2.2.1

    You can also get the error by overriding the official module you want to import by giving your module the same name.

    Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment.

    What is seaborn?

    seaborn is a Python data visualization library based on matplotlib.

    The simplest way to install seaborn is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.

    Always Use a Virtual Environment to Install Packages

    It is always best to install new libraries within a virtual environment. You should not install anything into your global Python interpreter when you develop locally. You may introduce incompatibilities between packages, or you may break your system if you install an incompatible version of a library that your operating system needs. Using a virtual environment helps compartmentalize your projects and their dependencies. Each project will have its environment with everything the code needs to run. Most ImportErrors and ModuleNotFoundErrors occur due to installing a library for one interpreter and trying to use the library with another interpreter. Using a virtual environment avoids this. In Python, you can use virtual environments and conda environments. We will go through how to install seaborn with both.

    How to Install seaborn on Windows Operating System

    First, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically on Windows for Python versions 2.7.9+ and 3.4+.

    You can check your Python version with the following command:

    python3 --version

    You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.

    python get-pip.py

    You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.

    pip --version
    virtualenv env

    You can activate the environment by typing the command:

    env\Scripts\activate

    You will see “env” in parenthesis next to the command line prompt. You can install seaborn within the environment by running the following command from the command prompt.

    python3 -m pip install seaborn

    We use python -m pip to execute pip using the Python interpreter we specify as Python. Doing this helps avoid ImportError when we try to use a package installed with one version of Python interpreter with a different version. You can use the command which python to determine which Python interpreter you are using.

    How to Install seaborn on Mac Operating System using pip

    Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:

    python3 --version
    Python 3.8.8

    Download pip by running the following curl command:

    curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

    The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.

    Install pip by running:

    python3 get-pip.py

    To install seaborn, first create the virtual environment:

    python3 -m venv env

    Then activate the environment using:

    source env/bin/activate 

    You will see “env” in parenthesis next to the command line prompt. You can install seaborn within the environment by running the following command from the command prompt.

    python3 -m pip install seaborn

    How to Install seaborn on Linux Operating Systems

    All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.

    Installing pip for Ubuntu, Debian, and Linux Mint

    sudo apt install python-pip3

    Installing pip for CentOS 8 (and newer), Fedora, and Red Hat

    sudo dnf install python-pip3

    Installing pip for CentOS 6 and 7, and older versions of Red Hat

    sudo yum install epel-release
    
    sudo yum install python-pip3

    Installing pip for Arch Linux and Manjaro

    sudo pacman -S python-pip

    Installing pip for OpenSUSE

    sudo zypper python3-pip

    seaborn installation on Linux with Pip

    To install seaborn, first create the virtual environment:

    python3 -m venv env

    Then activate the environment using:

    source env/bin/activate 

    You will see “env” in parenthesis next to the command line prompt. You can install seaborn within the environment by running the following command from the command prompt.

    Once you have activated your virtual environment, you can install seaborn using:

    python3 -m pip install seaborn

    Installing seaborn Using Anaconda

    Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda, you can create a virtual environment and install seaborn.

    To create a conda environment you can use the following command:

    conda create -n project python=3.8

    You can specify a different Python 3 version if you like. Ideally, choose the latest version of Python. Next, you will activate the project container. You will see “project” in parentheses next to the command line prompt.

    source activate project

    Now you’re ready to install seaborn using conda.

    Once you have installed Anaconda and created your conda environment, you can install seaborn using the following command:

    conda install -c anaconda seaborn

    Check seaborn Version

    Once you have successfully installed seaborn, you can check its version. If you used pip to install seaborn, you can use pip show from your terminal.

    python3 -m pip show seaborn
    Name: seaborn
    Version: 0.11.2
    Summary: seaborn: statistical data visualization
    Home-page: https://seaborn.pydata.org

    Second, within your python program, you can import seaborn and then reference the __version__ attribute:

    import seaborn
    print(seaborn.__version__)
    0.11.2

    If you used conda to install seaborn, you could check the version using the following command:

    conda list -f seaborn
    # Name                    Version                   Build  Channel
    seaborn                   0.11.2             pyhd3eb1b0_0    anaconda

    Using seaborn Example

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set_theme(style="darkgrid")
    
    # Load an example dataset
    fmri = sns.load_dataset("fmri")
    
    # Plot the responses for different events and regions
    sns.lineplot(x="timepoint", y="signal",
                 hue="region", style="event",
                 data=fmri)
    
    plt.show()

    seaborn fmri lineplot example

    Seaborn lineplot example

    Summary

    Congratulations on reading to the end of this tutorial.

    Go to the online courses page on Python to learn more about Python for data science and machine learning.

    For further reading on missing modules in Python, go to the article:

    • How to Solve Python ModuleNotFoundError: no module named ‘urllib2’.
    • How to Solve Python ModuleNotFoundError: no module named ‘colorama’
    • How to Solve Python ModuleNotFoundError: no module named ‘jinja2’

    Have fun and happy researching!

    This is a collection of answers to questions that are commonly raised about seaborn.

    Getting started#

    I’ve installed seaborn, why can’t I import it?#

    It looks like you successfully installed seaborn by doing pip install seaborn but it cannot be imported. You get an error like “ModuleNotFoundError: No module named ‘seaborn’” when you try.

    This is probably not a seaborn problem, per se. If you have multiple Python environments on your computer, it is possible that you did pip install in one environment and tried to import the library in another. On a unix system, you could check whether the terminal commands which pip, which python, and (if applicable) which jupyter point to the same bin/ directory. If not, you’ll need to sort out the definition of your $PATH variable.

    Two alternate patterns for installing with pip may also be more robust to this problem:

    • Invoke pip on the command line with python -m pip install <package> rather than pip install <package>

    • Use %pip install <package> in a Jupyter notebook to install it in the same place as the kernel

    I can’t import seaborn, even though it’s definitely installed!#

    You’ve definitely installed seaborn in the right place, but importing it produces a long traceback and a confusing error message, perhaps something like ImportError: DLL load failed: The specified module could not be found.

    Such errors usually indicate a problem with the way Python libraries are using compiled resources. Because seaborn is pure Python, it won’t directly encounter these problems, but its dependencies (numpy, scipy, matplotlib, and pandas) might. To fix the issue, you’ll first need to read through the traceback and figure out which dependency was being imported at the time of the error. Then consult the installation documentation for the relevant package, which might have advice for getting an installation working on your specific system.

    The most common culprit of these issues is scipy, which has many compiled components. Starting in seaborn version 0.12, scipy is an optional dependency, which should help to reduce the frequency of these issues.

    Why aren’t my plots showing up?#

    You’re calling seaborn functions — maybe in a terminal or IDE with an integrated IPython console — but not seeing any plots.)

    In matplotlib, there is a distinction between creating a figure and showing it, and in some cases it’s necessary to explicitly call matplotlib.pyplot.show() at the point when you want to see the plot. Because that command blocks by default and is not always desired (for instance, you may be executing a script that saves files to disk) seaborn does not deviate from standard matplotlib practice here.

    Yet most of the examples in the seaborn docs do not have this line, because there are multiple ways to avoid needing it. In a Jupyter notebook with the “inline” (default) or “widget” backends, matplotlib.pyplot.show() is automatically called after executing a cell, so any figures will appear in the cell’s outputs. You can also activate a more interactive experience by executing %matplotlib in any Jupyter or IPython interface or by calling matplotlib.pyplot.ion() anywhere in Python. Both methods will configure matplotlib to show or update the figure after every plotting command.

    Why is something printed after every notebook cell?#

    You’re using seaborn in a Jupyter notebook, and every cell prints something like <AxesSuplot:> or <seaborn.axisgrid.FacetGrid at 0x7f840e279c10> before showing the plot.

    Jupyter notebooks will show the result of the final statement in the cell as part of its output, and each of seaborn’s plotting functions return a reference to the matplotlib or seaborn object that contain the plot. If this is bothersome, you can suppress this output in a few ways:

    • Always assign the result of the final statement to a variable (e.g. ax = sns.histplot(...))

    • Add a semicolon to the end of the final statement (e.g. sns.histplot(...);)

    • End every cell with a function that has no return value (e.g. plt.show(), which isn’t needed but also causes no problems)

    • Add cell metadata tags, if you’re converting the notebook to a different representation

    Why do the plots look fuzzy in a Jupyter notebook?#

    The default “inline” backend (defined by IPython) uses an unusually low dpi (“dots per inch”) for figure output. This is a space-saving measure: lower dpi figures take up less disk space. (Also, lower dpi inline graphics appear physically smaller because they are represented as PNGs, which do not exactly have a concept of resolution.) So one faces an economy/quality tradeoff.

    You can increase the DPI by resetting the rc parameters through the matplotlib API, using

    plt.rcParams.update({"figure.dpi": 96})
    

    Or do it as you activate the seaborn theme:

    sns.set_theme(rc={"figure.dpi": 96})
    

    If you have a high pixel-density monitor, you can make your plots sharper using “retina mode”:

    %config InlineBackend.figure_format = "retina"
    

    This won’t change the apparent size of your plots in a Jupyter interface, but they might appear very large in other contexts (i.e. on GitHub). And they will take up 4x the disk space. Alternatively, you can make SVG plots:

    %config InlineBackend.figure_format = "svg"
    

    This will configure matplotlib to emit vector graphics with “infinite resolution”. The downside is that file size will now scale with the number and complexity of the artists in your plot, and in some cases (e.g., a large scatterplot matrix) the load will impact browser responsiveness.

    Tricky concepts#

    What do “figure-level” and “axes-level” mean?#

    You’ve encountered the term “figure-level” or “axes-level”, maybe in the seaborn docs, StackOverflow answer, or GitHub thread, but you don’t understand what it means.

    In brief, all plotting functions in seaborn fall into one of two categories:

    • “axes-level” functions, which plot onto a single subplot that may or may not exist at the time the function is called

    • “figure-level” functions, which internally create a matplotlib figure, potentially including multiple subplots

    This design is intended to satisfy two objectives:

    • seaborn should offer functions that are “drop-in” replacements for matplotlib methods

    • seaborn should be able to produce figures that show “facets” or marginal distributions on distinct subplots

    The figure-level functions always combine one or more axes-level functions with an object that manages the layout. So, for example, relplot() is a figure-level function that combines either scatterplot() or lineplot() with a FacetGrid. In contrast, jointplot() is a figure-level function that can combine multiple different axes-level functions — scatterplot() and histplot() by default — with a JointGrid.

    If all you’re doing is creating a plot with a single seaborn function call, this is not something you need to worry too much about. But it becomes relevant when you want to customize at a level beyond what the API of each function offers. It is also the source of various other points of confusion, so it is an important distinction understand (at least broadly) and keep in mind.

    This is explained in more detail in the tutorial and in this blog post.

    What is a “categorical plot” or “categorical function”?#

    Next to the figure-level/axes-level distinction, this concept is probably the second biggest source of confusing behavior.

    Several seaborn functions are referred to as “categorical” because they are designed to support a use-case where either the x or y variable in a plot is categorical (that is, the variable takes a finite number of potentially non-numeric values).

    At the time these functions were written, matplotlib did not have any direct support for non-numeric data types. So seaborn internally builds a mapping from unique values in the data to 0-based integer indexes, which is what it passes to matplotlib. If your data are strings, that’s great, and it more-or-less matches how matplotlib now handles string-typed data.

    But a potential gotcha is that these functions always do this, even if both the x and y variables are numeric. This gives rise to a number of confusing behaviors, especially when mixing categorical and non-categorical plots (e.g., a combo bar-and-line plot).

    The v0.12 release added a native_scale parameter to stripplot() and swarmplot(), which provides control over this behavior. It will be rolled out to other categorical functions in future releases. But the current behavior will almost certainly remain the default, so this is an important API wrinkle to understand.

    Specifying data#

    How does my data need to be organized?#

    To get the most out of seaborn, your data should have a “long-form” or “tidy” representation. In a dataframe, this means that each variable has its own column, each observation has its own row, and each value has its own cell. With long-form data, you can succinctly and exactly specify a visualization by assigning variables in the dataset (columns) to roles in the plot.

    Data organization is a common stumbling block for beginners, in part because data are often not collected or stored in a long-form representation. Therefore, it is often necessary to reshape the data using pandas before plotting. Data reshaping can be a complex undertaking, requiring both a solid grasp of dataframe structure and knowledge of the pandas API. Investing some time in developing this skill can pay large dividends.

    But while seaborn is most powerful when provided with long-form data, nearly every seaborn function will accept and plot “wide-form” data too. You can trigger this by passing an object to seaborn’s data= parameter without specifying other plot variables (x, y, …). You’ll be limited when using wide-form data: each function can make only one kind of wide-form plot. In most cases, seaborn tries to match what matplotlib or pandas would do with a dataset of the same structure. Reshaping your data into long-form will give you substantially more flexibility, but it can be helpful to take a quick look at your data very early in the process, and seaborn tries to make this possible.

    Understanding how your data should be represented — and how to get it that way if it starts out messy — is very important for making efficient and complete use of seaborn, and it is elaborated on at length in the user-guide.

    Does seaborn only work with pandas?#

    Generally speaking, no: seaborn is quite flexible about how your dataset needs to be represented.

    In most cases, long-form data represented by multiple vector-like types can be passed directly to x, y, or other plotting parameters. Or you can pass a dictionary of vector types to data rather than a DataFrame. And when plotting with wide-form data, you can use a 2D numpy array or even nested lists to plot in wide-form mode.

    There are a couple older functions (namely, catplot() and lmplot()) that do require you to pass a pandas.DataFrame. But at this point, they are the exception, and they will gain more flexibility over the next few release cycles.

    Layout problems#

    How do I change the figure size?#

    This is going to be more complicated than you might hope, in part because there are multiple ways to change the figure size in matplotlib, and in part because of the figure-level/axes-level distinction in seaborn.

    In matplotlib, you can usually set the default size for all figures through the rc parameters, specifically figure.figsize. And you can set the size of an individual figure when you create it (e.g. plt.subplots(figsize=(w, h))). If you’re using an axes-level seaborn function, both of these will work as expected.

    Figure-level functions both ignore the default figure size and parameterize the figure size differently. When calling a figure-level function, you can pass values to height= and aspect= to set (roughly) the size of each subplot. The advantage here is that the size of the figure automatically adapts when you add faceting variables. But it can be confusing.

    Fortunately, there’s a consistent way to set the exact figure size in a function-independent manner. Instead of setting the figure size when the figure is created, modify it after you plot by calling obj.figure.set_size_inches(...), where obj is either a matplotlib axes (usually assigned to ax) or a seaborn FacetGrid (usually assigned to g).

    Note that FacetGrid.figure exists only on seaborn >= 0.11.2; before that you’ll have to access FacetGrid.fig.

    Also, if you’re making pngs (or in a Jupyter notebook), you can — perhaps surprisingly — scale all your plots up or down by changing the dpi.

    Why isn’t seaborn drawing the plot where I tell it to?#

    You’ve explicitly created a matplotlib figure with one or more subplots and tried to draw a seaborn plot on it, but you end up with an extra figure and a blank subplot. Perhaps your code looks something like

    f, ax = plt.subplots()
    sns.catplot(..., ax=ax)
    

    This is a figure-level/axes-level gotcha. Figure-level functions always create their own figure, so you can’t direct them towards an existing axes the way you can with axes-level functions. Most functions will warn you when this happens, suggest the appropriate axes-level function, and ignore the ax= parameter. A few older functions might put the plot where you want it (because they internally pass ax to their axes-level function) while still creating an extra figure. This latter behavior should be considered a bug, and it is not to be relied on.

    The way things currently work, you can either set up the matplotlib figure yourself, or you can use a figure-level function, but you can’t do both at the same time.

    Why can’t I draw a line over a bar/box/strip/violin plot?#

    You’re trying to create a single plot using multiple seaborn functions, perhaps by drawing a lineplot or regplot over a barplot or violinplot. You expect the line to go through the mean value for each box (etc.), but it looks to be misalgined, or maybe it’s all the way off to the side.

    You are trying to combine a “categorical plot” with another plot type. If your x variable has numeric values, it seems like this should work. But recall: seaborn’s categorical plots map unique values on the categorical axis to integer indexes. So if your data have unique x values of 1, 6, 20, 94, the corresponding plot elements will get drawn at 0, 1, 2, 3 (and the tick labels will be changed to represent the actual value).

    The line or regression plot doesn’t know that this has happened, so it will use the actual numeric values, and the plots won’t line up at all.

    As of now, there are two ways to work around this. In situations where you want to draw a line, you could use the (somewhat misleadingly named) pointplot() function, which is also a “categorical” function and will use the same rules for drawing the plot. If this doesn’t solve the problem (for one, it’s not as visually flexible as lineplot(), you could implement the mapping from actual values to integer indexes yourself and draw the plot that way:

    unique_xs = sorted(df["x"].unique())
    sns.violinplot(data=df, x="x", y="y")
    sns.lineplot(data=df, x=df["x"].map(unique_xs.index), y="y")
    

    This is something that will be easier in a planned future release, as it will become possible to make the categorical functions treat numeric data as numeric. (As of v0.12, it’s possible only in stripplot() and swarmplot(), using native_scale=True).

    How do I move the legend?#

    When applying a semantic mapping to a plot, seaborn will automatically create a legend and add it to the figure. But the automatic choice of legend position is not always ideal.

    With seaborn v0.11.2 or later, use the move_legend() function.

    On older versions, a common pattern was to call ax.legend(loc=...) after plotting. While this appears to move the legend, it actually replaces it with a new one, using any labeled artists that happen to be attached to the axes. This does not consistently work across plot types. And it does not propagate the legend title or positioning tweaks that are used to format a multi-variable legend.

    The move_legend() function is actually more powerful than its name suggests, and it can also be used to modify other legend parameters (font size, handle length, etc.) after plotting.

    Other customizations#

    How can I can I change something about the figure?#

    You want to make a very specific plot, and seaborn’s defaults aren’t doing it for you.

    There’s basically a four-layer hierarchy to customizing a seaborn figure:

    1. Explicit seaborn function parameters

    2. Passed-through matplotlib keyword arguments

    3. Matplotlib axes methods

    4. Matplotlib artist methods

    First, read through the API docs for the relevant seaborn function. Each has a lot of parameters (probably too many), and you may be able to accomplish your desired customization using seaborn’s own API.

    But seaborn does delegate a lot of customization to matplotlib. Most functions have **kwargs in their signature, which will catch extra keyword arguments and pass them through to the underlying matplotlib function. For example, scatterplot() has a number of parameters, but you can also use any valid keyword argument for matplotlib.axes.Axes.scatter(), which it calls internally.

    Passing through keyword arguments lets you customize the artists that represent data, but often you will want to customize other aspects of the figure, such as labels, ticks, and titles. You can do this by calling methods on the object that seaborn’s plotting functions return. Depending on whether you’re calling an axes-level or figure-level function, this may be a matplotlib.axes.Axes object or a seaborn wrapper (such as seaborn.FacetGrid). Both kinds of objects have numerous methods that you can call to customize nearly anything about the figure. The easiest thing is usually to call matplotlib.axes.Axes.set() or seaborn.FacetGrid.set(), which let you modify multiple attributes at once, e.g.:

    ax = sns.scatterplot(...)
    ax.set(
        xlabel="The x label",
        ylabel="The y label",
        title="The title"
        xlim=(xmin, xmax),
        xticks=[...],
        xticklabels=[...],
    )
    

    Finally, the deepest customization may require you to reach “into” the matplotlib axes and tweak the artists that are stored on it. These will be in artist lists, such as ax.lines, ax.collections, ax.patches, etc.

    Warning: Neither matplotlib nor seaborn consider the specific artists produced by their plotting functions to be part of stable API. Because it’s not possible to gracefully warn about upcoming changes to the artist types or the order in which they are stored, code that interacts with these attributes could break unexpectedly. With that said, seaborn does try hard to avoid making this kind of change.

    Wait, I need to learn how to use matplotlib too?#

    It really depends on how much customization you need. You can certainly perform a lot of exploratory data analysis while primarily or exclusively interacting with the seaborn API. But, if you’re polishing a figure for a presentation or publication, you’ll likely find yourself needing to understand at least a little bit about how matplotlib works. Matplotlib is extremely flexible, and it lets you control literally everything about a figure if you drill down far enough.

    Seaborn was originally designed with the idea that it would handle a specific set of well-defined operations through a very high-level API, while letting users “drop down” to matplotlib when they desired additional customization. This can be a pretty powerful combination, and it works reasonably well if you already know how to use matplotlib. But as seaborn as gained more features, it has become more feasible to learn seaborn first. In that situation, the need to switch APIs tends to be a bit more confusing / frustrating. This has motivated the development of seaborn’s new objects interface, which aims to provide a more cohesive API for both high-level and low-level figure specification. Hopefully, it will alleviate the “two-library problem” as it matures.

    With that said, the level of deep control that matplotlib affords really can’t be beat, so if you care about doing very specific things, it really is worth learning.

    How do I use seaborn with matplotlib’s object-oriented interface?#

    You prefer to use matplotlib’s explicit or “object-oriented” interface, because it makes your code easier to reason about and maintain. But the object-orient interface consists of methods on matplotlib objects, whereas seaborn offers you independent functions.

    This is another case where it will be helpful to keep the figure-level/axes-level distinction in mind.

    Axes-level functions can be used like any matplotlib axes method, but instead of calling ax.func(...), you call func(..., ax=ax). They also return the axes object (which they may have created, if no figure was currently active in matplotlib’s global state). You can use the methods on that object to further customize the plot even if you didn’t start with matplotlib.pyplot.figure() or matplotlib.pyplot.subplots():

    ax = sns.histplot(...)
    ax.set(...)
    

    Figure-level functions can’t be directed towards an existing figure, but they do store the matplotlib objects on the FacetGrid object that they return (which seaborn docs always assign to a variable named g).

    If your figure-level function created only one subplot, you can access it directly:

    g = sns.displot(...)
    g.ax.set(...)
    

    For multiple subplots, you can either use FacetGrid.axes (which is always a 2D array of axes) or FacetGrid.axes_dict (which maps the row/col keys to the corresponding matplotlib object):

    g = sns.displot(..., col=...)
    for col, ax in g.axes_dict.items():
        ax.set(...)
    

    But if you’re batch-setting attributes on all subplots, use the FacetGrid.set() method rather than iterating over the individual axes:

    g = sns.displot(...)
    g.set(...)
    

    To access the underlying matplotlib figure, use FacetGrid.figure on seaborn >= 0.11.2 (or FacetGrid.fig on any other version).

    Can I annotate bar plots with the bar values?#

    Nothing like this is built into seaborn, but matplotlib v3.4.0 added a convenience function (matplotlib.axes.Axes.bar_label()) that makes it relatively easy. Here are a couple of recipes; note that you’ll need to use a different approach depending on whether your bars come from a figure-level or axes-level function:

    # Axes-level
    ax = sns.histplot(df, x="x_var")
    for bars in ax.containers:
        ax.bar_label(bars)
    
    # Figure-level, one subplot
    g = sns.displot(df, x="x_var")
    for bars in g.ax.containers:
        g.ax.bar_label(bars)
    
    # Figure-level, multiple subplots
    g = sns.displot(df, x="x_var", col="col_var)
    for ax in g.axes.flat:
        for bars in ax.containers:
            ax.bar_label(bars)
    

    Can I use seaborn in dark mode?#

    There’s no direct support for this in seaborn, but matplotlib has a “dark_background” style-sheet that you could use, e.g.:

    sns.set_theme(style="ticks", rc=plt.style.library["dark_background"])
    

    Note that “dark_background” changes the default color palette to “Set2”, and that will override any palette you define in set_theme(). If you’d rather use a different color palette, you’ll have to call sns.set_palette() separately. The default seaborn palette (“deep”) has poor contrast against a dark background, so you’d be better off using “muted”, “bright”, or “pastel”.

    Statistical inquiries#

    Can I access the results of seaborn’s statistical transformations?#

    Because seaborn performs some statistical operations as it builds plots (aggregating, bootstrapping, fitting regression models), some users would like access to the statistics that it computes. This is not possible: it’s explicitly considered out of scope for seaborn (a visualization library) to offer an API for interrogating statistical models.

    If you simply want to be diligent and verify that seaborn is doing things correctly (or that it matches your own code), it’s open-source, so feel free to read the code. Or, because it’s Python, you can call into the private methods that calculate the stats (just don’t do this in production code). But don’t expect seaborn to offer features that are more at home in scipy or statsmodels.

    Can I show standard error instead of a confidence interval?#

    As of v0.12, this is possible in most places, using the new errorbar API (see the tutorial for more details).

    Why does the y axis for a KDE plot go above 1?#

    You’ve estimated a probability distribution for your data using kdeplot(), but the y axis goes above 1. Aren’t probabilities bounded by 1? Is this a bug?

    This is not a bug, but it is a common confusion (about kernel density plots and probability distributions more broadly). A continuous probability distribution is defined by a probability density function, which kdeplot() estimates. The probability density function does not output a probability: a continuous random variable can take an infinite number of values, so the probability of observing any specific value is infinitely small. You can only talk meaningfully about the probability of observing a value that falls within some range. The probability of observing a value that falls within the complete range of possible values is 1. Likewise, the probability density function is normalized so that the area under it (that is, the integral of the function across its domain) equals 1. If the range of likely values is small, the curve will have to go above 1 to make this possible.

    Common curiosities#

    Why is seaborn imported as sns?#

    This is an obscure reference to the namesake of the library, but you can also think of it as “seaborn name space”.

    Why is ggplot so much better than seaborn?#

    Good question. Probably because you get to use the word “geom” a lot, and it’s fun to say. “Geom”. “Geeeeeooom”.

    Trying to fix the Python nameerror: name sns is not defined error message…

    However, you are struggling to fix it? Then, keep on reading.

    In this article, we’ll show how to fix nameerror name sns is not defined in simple and easy way.

    What is “sns” module?

    The “sns” module is the abbreviation for the seaborn library, which is a Python data visualization library based on matplotlib.

    This module provides a high-level interface for drawing attractive and informative statistical graphics.

    In addition to that, this library is commonly imported with the shorthand sns, like the following:

     ✅ import seaborn as sns

    The error message nameerror: name sns is not defined occurs when you’re trying to use the “sns” module without importing it first or you did not install the seaborn library.

    For example:

    import matplotlib.pyplot as plt
    
    
    plt.plot([1, 2, 3, 4, 5])
    sns.set_style("whitegrid")  # This line will cause the error
    plt.show()
    

    If you try to run this code, it will throw a NameError that indicates name sns is not defined.

    This error message indicates that you’re trying to use a variable or function named sns.

    However, the Python interpreter does not recognize what sns is, because it is not defined or imported.

    Why does this error occur?

    The nameerror name sns is not defined error message can be raised if you forget to define a variable or if you’re trying to use a library like seaborn (which is commonly imported as sns) but haven’t imported it correctly.

    How to fix “nameerror: name sns is not defined”?

    To fix the Python nameerror name ‘sns’ is not defined error, you need to ensure that the seaborn library is installed and it is imported correctly and assigned to the variable “sns.”

    Here are the following solutions that you use to finally resolved the error.

    Solution 1: Install seaborn library

    When you haven’t installed the seaborn library yet, you can use the “pip install” command to install the library in your environment.

    Here are the steps to install the seaborn library:

    1. Go to Anaconda Command Prompt.
    2.  Input activate tensorflow or conda activate.
    3.  Then, install the seaborn.

    You can also install it directly in your command prompt or terminal. Here’s the command that you can use to install the seaborn library:

    pip install seaborn

    Solution 2: Import seaborn as sns

    After the seaborn library is installed you may now Import seaborn and assign it to the variable sns.

    You can do this by adding the following line at the beginning of your code.

    For example:

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    # Set the style of the plot
    sns.set_style("darkgrid")
    
    # Create some data
    x = [1, 2, 3, 4, 5]
    y = [2, 4, 6, 8, 10]
    
    # Create a plot
    plt.plot(x, y)
    
    # Show the plot
    plt.show()
    

    As you have noticed, you simply need to import Seaborn as “sns” in your code.

    Once you have done that, the “sns.set_style()” function will be recognized by Python, and the code will run without any errors.

    Output:

    Import seaborn as sns fix the nameerror: name sns is not defined

    Solution 3: Import seaborn with a different variable name

    If you don’t want to use the variable name sns, you can import seaborn with a different variable name.

    For example:

    import seaborn as sb
    import matplotlib.pyplot as plt
    
    # Set the style of the plot
    sb.set_style("darkgrid")
    
    # Create some data
    x = [1, 2, 3, 4, 5]
    y = [2, 4, 6, 8, 10]
    
    # Create a plot
    plt.plot(x, y)

    You could use import seaborn and assign it to the variable sb to fix the error. The output would be the same as what you can see in the solution 2 above.

    Conclusion

    In conclusion, the error message nameerror: name sns is not defined occurs when you’re trying to use the “sns” module without importing it first or you did not install the seaborn library.

    This article explores what this error is all about and already provides solutions to help you fix this error.

    You could also check out other “nameerror” articles that may help you in the future if you encounter them.

    • Nameerror name ‘json’ is not defined
    • Nameerror name data is not defined
    • Nameerror name requests is not defined

    We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊

    Понравилась статья? Поделить с друзьями:
  • Ilife v55 робот пылесос ошибка e04
  • Immergas ошибка е44
  • Iis включить отображение ошибок
  • Igfxtray exe ошибка приложения
  • Ilife v55 ошибка е06 что делать