Feel free to change the label of the legend in Seaborn in python

Articles for people like this

--People who have recently started using seaborn with python and want to do boxplot, violinplot, etc. --People who want to set labels with their own character strings using violinplot and boxplot --People who are in trouble because the label is set automatically when it is seaborn

Solution

Set the handle of the legend Easy solution with the following two lines!

python


handler, label = ax.get_legend_handles_labels()
ax.legend(handler, ["label1", "label2"])

Plot example using Titanic data

Download data

We will use titanic data as an example. The titanic dataset is described in many places. For example, the following article. Reference: "Titanic: Tabular data set of survival status (13 items such as age and gender) of Titanic passengers" https://www.atmarkit.co.jp/ait/articles/2007/02/news016.html

python


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set("talk")

df = sns.load_dataset('titanic')
df.head()

The output result looks like this.

WS000147.JPG

Age distribution by passenger class

Here, we will plot the age distribution for each pclass (passenger class).

python


sns.violinplot(data=df, x='pclass', y='age')

ダウンロード (3).png

Looking at the figure, we can see that there are many younger generations in pclass3. Dig deeper, "Is there a difference in life and death in the age distribution of each class?" I would like to see.

python


fig,ax=plt.subplots()
sns.violinplot(data=df, x='pclass', y='age',hue="alive",split=True, ax=ax)
ax.legend(loc='upper left',bbox_to_anchor=(1.05,1))

ダウンロード.png

You can divide the violin plot into two by specifying the hue. The legend is placed outside the figure for clarity.

Label change (main subject)

It's finally the main subject. What is worrisome here is the legend label. If you say no or yes, you don't know what it is when you look at it later. This is because the content no / yes of the alive column of df is specified as it is in the label.

Therefore, get the handle of label and specify it directly.

python


fig,ax=plt.subplots()
sns.violinplot(data=df, x='pclass', y='age',hue="alive",split=True, ax=ax)
ax.legend(loc='upper left',bbox_to_anchor=(1.05,1))
handler, label = ax.get_legend_handles_labels()
ax.legend(handler, ["dead","alive"],loc='upper left',bbox_to_anchor=(1.05,1))

ダウンロード (1).png

You can safely determine if the label is dead / alive and there is no difference between life and death even if you look at it later.

By the way, as I found out that it was divided by life and death

--When pclass 2 and 3, the percentage of alive is high in younger age groups such as teens. --In pclass3, the ratio of dead and alive is about the same in the 30s, but in pclass2, the ratio of dead is high. --P class 1 has a significantly higher percentage of dead in their 50s and older.

You can see various things such as.

swarmplot example

Of course you can do the same with swarm lot.

python


fig,ax=plt.subplots()
sns.swarmplot(data=df, x='pclass', y='age',hue="alive",dodge=True, ax=ax)
ax.legend(loc='upper left',bbox_to_anchor=(1.05,1))
handler, label = ax.get_legend_handles_labels()
ax.legend(handler, ["dead","alive"],loc='upper left',bbox_to_anchor=(1.05,1))

Summary

--When plotting with seaborn, the contents of the column become labels --You can freely edit the label by getting the handle and specifying it directly.

Reference article

Python: Try visualization with seaborn https://blog.amedama.jp/entry/seaborn-plot

Recommended Posts

Feel free to change the label of the legend in Seaborn in python
Feel free to write a test with nose (in the case of + gevent)
How to get the number of digits in Python
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
Change the standard output destination to a file in Python
In the python command python points to python3.8
Change the Python version of Homebrew
Feel free to encrypt the disk
[Python] Change the alphabet to numbers
How to change the log level of Azure SDK for Python
How to know the internal structure of an object in Python
[Python] PCA scratch in the example of "Introduction to multivariate analysis"
How to change the color of just the button pressed in Tkinter
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
How to check the memory size of a variable in Python
Output the contents of ~ .xlsx in the folder to HTML with Python
I wrote the code to write the code of Brainf * ck in python
How to check the memory size of a dictionary in Python
Change the active version in Pyenv from anaconda to plain Python
Check the behavior of destructor in Python
Script to change the description of fasta
The result of installing python in Anaconda
The basics of running NoxPlayer in Python
In search of the fastest FizzBuzz in Python
Change the saturation and brightness of color specifications like # ff000 in python 2.5
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
[Introduction to Python] Thorough explanation of the character string type used in Python!
I made a program to check the size of a file in Python
An example of the answer to the reference question of the study session. In python.
How to use the C library in Python
[Python] Sort the list of pathlib.Path in natural sort
Change the device (drive) label in vfat format.
[Python] How to change the date format (display format)
Summary of how to import files in Python 3
[Python] Get / edit the scale label of the figure
Get the caller of a function in Python
Match the distribution of each group in Python
View the result of geometry processing in Python
To dynamically replace the next method in python
Make a copy of the list in Python
Summary of how to use MNIST in Python
Draw graphs in Julia ... Leave the graphs to Python
Change the decimal point of logging from, to.
Find the divisor of the value entered in python
[Python] Display the Altair legend in the plot area
Try the free version of Progate [Python I]
The trick to write flatten concisely in python
How to get the files in the [Python] folder
Find the solution of the nth-order equation in python
The story of reading HSPICE data in Python
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
Solving the equation of motion in Python (odeint)
Output in the form of a python array
I want to display the progress in Python!
Various ways to read the last line of a csv file in Python
How to pass the execution result of a shell command in a list in Python
I want to use Python in the environment of pyenv + pipenv on Windows 10
In Python, change the behavior of the method depending on how it is called