search
HomeBackend DevelopmentPython TutorialDetailed explanation of Python's Seaborn (data visualization)

This article brings you relevant knowledge about python, which mainly introduces related issues about Seaborn, including scatter plots, line charts, bar charts, etc. for data visualization processing Let’s take a look at the content below, I hope it will be helpful to everyone.

Detailed explanation of Python's Seaborn (data visualization)

Recommended learning: python video tutorial

1. Install seaborn

Installation:

pip install seaborn

##Import:

import seaborn as sns


2. Prepare data

Before we officially start, we first use the following code to prepare a set of data for convenience Demonstrate use.

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snspd.set_option('display.unicode.east_asian_width', True)df1 = pd.DataFrame(    {'数据序号': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],     '厂商编号': ['001', '001', '001', '002', '002', '002', '003', '003', '003', '004', '004', '004'],     '产品类型': ['AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC'],     'A属性值': [40, 70, 60, 75, 90, 82, 73, 99, 125, 105, 137, 120],     'B属性值': [24, 36, 52, 32, 49, 68, 77, 90, 74, 88, 98, 99],     'C属性值': [30, 36, 55, 46, 68, 77, 72, 89, 99, 90, 115, 101]    })print(df1)

Generate a set of data as follows:

ONE posit Border

Detailed explanation of Pythons Seaborn (data visualization)

3.1 Set the background style

The sns.set_style() method is used to set the style, and the built-in style here uses the background color to represent the name, but Actual content is not limited to background color.


sns.set_style()

The background styles that can be selected are:

whitegrid white grid


dark gray background

  • white white background
  • ticks White background with ticks around it
  • ## 
  • sns.set()
  • sns.set_style( "darkgrid") sns.set_style("whitegrid")
  • sns.set_style("dark")
sns.set_style("white")
## sns.set_style(“ticks”)





 Where sns.set() means using a custom style. If no parameters are passed in, the default is gray. Grid background style. If there is no set() or set_style(), the background will be white.

  A possible bug: the "ticks" style is invalid for images drawn using the relplot() method.



3.3 Others

The seaborn library is encapsulated based on the matplotlib library, and its encapsulated style can make our drawing work more convenient. The commonly used statements in the matplotlib library are still valid when using the seaborn library.

  About setting other style-related properties, such as fonts, one detail to note is that these codes must be written after sns.set_style() to be effective. For example, the code to set the font to bold (to avoid Chinese garbled characters):


##plt.rcParams['font.sans-serif'] = [' SimHei']


If the style is set behind it, the set font will override the set style, thus generating a warning. The same goes for other attributes.

3.2 Border control

sns.despine() method

# 移除顶部和右部边框,只保留左边框和下边框sns.despine()# 使两个坐标轴相隔一段距离(以10长度为例)sns.despine(offet=10,trim=True)# 移除左边框sns.despine(left=True)# 移除指定边框 (以只保留底部边框为例)sns.despine(fig=None, ax=None, top=True, right=True, left=True, bottom=False, offset=None, trim=False)

4 . Draw a scatter plot

Use the seaborn library to draw a scatter plot. You can use the replot() method or the scatter() method.

The parameter kind of the replot method defaults to 'scatter', which means drawing a scatter plot.

The hue parameter indicates that in this dimension, it is distinguished by color

① Draw a scatter plot of the A attribute value and data sequence number, red scatter points, gray grid, keep the left , lower border

sns.set_style('darkgrid') plt.rcParams['font.sans-serif'] = ['SimHei']

sns.relplot(x='data serial number', y='A attribute value', data=df1, color='red')

plt.show()

       


② Draw a scatter plot for the A attribute value and data sequence number. The scatter points display different colors according to different product types.
White grid, left and bottom borders:

sns.set_style('whitegrid')
plt.rcParams['font.sans-serif'] = ['SimHei']
sns.relplot(x=' Data serial number', y='A attribute value', hue='product type', data=df1)
plt.show()

    Detailed explanation of Pythons Seaborn (data visualization)


③Plot the values ​​of the three fields A attribute, B attribute, and C attribute on the same graph in different styles (draw a scatter plot). The x-axis data is [0,2,4 ,6,8…]
ticks style (frame lines in all four directions are required), the font uses italics

##sns.set_style('ticks') plt.rcParams['font.sans-serif'] = ['STKAITI']
df2 = df1.copy()
df2.index = list(range(0, len(df2)*2, 2 ))
dfs = [df2['A attribute value'], df2['B attribute value'], df2['C attribute value']]
sns.scatterplot(data=dfs)
plt .show()

 plicity Use the replot() method or the lineplot() method.

Detailed explanation of Pythons Seaborn (data visualization)

5.1 Use the replot() method

sns.replot() draws a scatter chart by default. To draw a line chart, just change the kind parameter to "line" .

Requirements: Draw a line chart of A attribute value and data serial number,

gray grid, global font is italics; and adjust the font size of the title and two-axis labels,

and The distance between the coordinate system and the edge of the canvas (the distance is set because the font is not fully displayed):


##sns.set(rc={'font.sans-serif ': "STKAITI"})
sns.relplot(x='data serial number', y='A attribute value', data=df1, color='purple', kind='line')
plt. title("Draw a line chart", fontsize=18)
plt.xlabel('num', fontsize=18)
plt.ylabel('A attribute value', fontsize=16)
plt.subplots_adjust (left=0.15, right=0.9, bottom=0.1, top=0.9)

plt.show()


          




Requirements: Draw A attribute polylines for different product types (three lines in one picture), whitegrid style, italic font.

Detailed explanation of Pythons Seaborn (data visualization)

sns.set_style("whitegrid")
plt.rcParams['font.sans-serif'] = ['STKAITI']

sns.relplot (x='data serial number', y='A attribute value', hue='product type', data=df1, kind='line') plt.title("Draw a line chart", fontsize=18)
plt.xlabel('num', fontsize=18)
plt.ylabel('A attribute value', fontsize=16)

plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1 , top=0.9)
plt.show()



ˆ ˆ ˆ ˆ ˆ ˆ The values ​​of the three fields A, B, and C are drawn in different styles on the same chart (drawing a line chart). The x-axis data is [0,2,4,6,8…]
◆ darkkgrid style (Frame lines in all four directions must be included), use italics for fonts, and add x-axis labels, y-axis labels and titles. The edge distance is appropriate.



sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['STKAITI']

df2 = df1.copy()Detailed explanation of Pythons Seaborn (data visualization) df2.index = list(range(0, len(df2)*2, 2))

dfs = [df2['A attribute value'], df2['B attribute value'], df2['C attribute value']]
sns.relplot(data=dfs, kind=“line”)

plt.title(“Draw a line chart”, fontsize=18) plt.xlabel('num', fontsize=18)
plt.ylabel('A attribute value', fontsize=16) plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top= 0.9)
plt.show()

∣ ∣ ∣ ∣ posit

##

Horizontal multiple subgraph col

##sns.set_style('darkgrid') plt.rcParams['font.sans-serif'] = [ 'STKAITI']
sns.relplot(data=df1, x="A attribute value", y="B attribute value", kind="line", col="manufacturer number")
plt.subplots_adjust (left=0.05, right=0.95, bottom=0.1, top=0.9)
plt.show()

Detailed explanation of Pythons Seaborn (data visualization)

##Vertical Multiple subgraph row

##sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['STKAITI']

sns.relplot(data=df1, x="A attribute value", y="B attribute value", kind="line", row="Manufacturer number") plt.subplots_adjust(left=0.15, right= 0.9, bottom=0.1, top=0.95)
plt.show()


##  ˆ ˆ ˆ ˆ ˆ ˆ ˆ

##5.2 Use the lineplot() method

Detailed explanation of Pythons Seaborn (data visualization)

Use the lineplot() method to draw a line chart. Other details are basically the same as above. The sample code is as follows:

sns.set_style('darkgrid') plt.rcParams['font.sans-serif'] = ['STKAITI']

sns.lineplot(x='data serial number', y='A attribute value', data=df1, color='purple' )
plt.title("Draw a line chart", fontsize=18)

plt.xlabel('num', fontsize=18) plt.ylabel('A attribute value', fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()


## ONE posit

##sns.set_style('darkgrid')

plt.rcParams['font.sans-serif'] = ['STKAITI']
df2 = df1.copy()

df2.index = list(range(0, len(df2)*2, 2))Detailed explanation of Pythons Seaborn (data visualization) dfs = [df2['A attribute value'], df2['B attribute value'], df2[' C attribute value']]

sns.lineplot(data=dfs)
plt.title("Draw a line chart", fontsize=18)
plt.xlabel('num', fontsize=18)

plt.ylabel('A attribute value', fontsize=16) plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()



  ˆ ˆ ˆ ˆ



6. Drawing the histogram displot()

The sns.displot() method is used to draw the histogram.

Detailed explanation of Pythons Seaborn (data visualization)

bins=6 indicates that the drawing is divided into six intervals
rug=True indicates that small thin bars of observation are displayed on the x-axis

kde=True indicates that the kernel density curve is displayed

sns.set_style('darkgrid')

plt.rcParams['font.sans-serif'] = ['STKAITI'] sns.displot(data =df1[['C attribute value']], bins=6, rug=True, kde=True)
plt.title("Histogram", fontsize=18)
plt.xlabel('C attribute value', fontsize=18)
plt.ylabel('quantity', fontsize=16)

plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt. show()



ˆ ˆ ˆ ˆ ˜



#sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['STKAITI']
np.random.seed (13)

Y = np.random.randn(300)
sns.displot(Y, bins=9, rug=True, kde=True)

plt.title("Histogram", fontsize =18)Detailed explanation of Pythons Seaborn (data visualization) plt.xlabel('C attribute value', fontsize=18)

plt.ylabel('Quantity', fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)

plt.show()

 ˆ ˆ ˆ ˆ ˆ ˜

##The barplot() method is used to draw the bar chart

The product type field data is used as the x-axis data, and the A attribute value data is used as the y-axis data. Classify according to different manufacturer number fields.
details as follows:

sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['STKAITI']
sns.barplot(x="Product Type ", y='A attribute value', hue="Manufacturer number", data=df1)
plt.title("Bar chart", fontsize=18)
plt.xlabel('Product type', fontsize=18)
plt.ylabel('quantity', fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.15, top=0.9)
plt.show()

ˆ ˆ ˆ ˆ ˜ . Detailed explanation of Pythons Seaborn (data visualization) The main parameters are x, y, data. Represents x-axis data, y-axis data and data set data respectively.


In addition, as mentioned above, you can also specify categorical variables through hue;

Specify column categorical variables through col to draw horizontal multiple subgraphs;

Specify row categorical variables through row , to draw vertical multiple sub-pictures;

Use col_wrap to control the number of sub-pictures in each row; Use size to control the height of sub-pictures;
Use markers to control the shape of points.

Let's perform linear regression on the X attribute value and Y attribute value. The code is as follows:




sns.set_style('darkgrid')
plt. rcParams['font.sans-serif'] = ['STKAITI']
sns.lmplot(x="A attribute value", y='B attribute value', data=df1)
plt.title( "Linear regression model", fontsize=18)

plt.xlabel('A attribute value', fontsize=18)
plt.ylabel('B attribute value', fontsize=16)

plt.subplots_adjust (left=0.15, right=0.9, bottom=0.15, top=0.9) plt.show()



ˆ ˆ ˆ ˆ ˆ ˆ


9. Drawing the kernel density map kdeplot()

Detailed explanation of Pythons Seaborn (data visualization)

9.1 General kernel density map

Drawing the sum density map can make us more intuitive can clearly see the distribution characteristics of the sample data. The method used to draw kernel density plots is the kdeplot() method.

Draw a kernel density map for the A attribute value and B attribute value. Set shade to True to display the surrounding shadow, otherwise only lines.


sns.set_style('darkgrid')
plt.rcParams['font.sans-serif'] = ['STKAITI']
sns.kdeplot (df1["A attribute value"], shade=True, data=df1, color='r')
sns.kdeplot(df1["B attribute value"], shade=True, data=df1, color= 'g')

plt.title("Kernel density plot", fontsize=18)
plt.xlabel('Value', fontsize=18)

plt.subplots_adjust(left=0.15, right=0.9 , bottom=0.15, top=0.9) plt.show()



ˆ ˆ ˆ ˆ ˆ


9.2 Marginal kernel density map

The sns.jointplot() method is used when drawing the marginal kernel density map. The parameter kind should be "kde". When using this method, the dark style is used by default. It is not recommended to add other styles manually, otherwise the image may not display properly. Detailed explanation of Pythons Seaborn (data visualization)


plt.rcParams['font.sans-serif'] = ['STKAITI']

sns.jointplot(x=df1["A attribute value"] , y=df1["B attribute value"], kind="kde", space=0) plt.show()

∣ ∣ ∣ ∣ ∣

10. Draw box plot boxplot()

Detailed explanation of Pythons Seaborn (data visualization)

The boxplot() method is used to draw box plots.
The basic parameters are x, y, data.

 In addition, there can also be hue indicating the classification field

width can adjust the width of the cabinet

notch indicates whether the middle cabinet displays a gap, and the default False does not display it.


In view of the fact that the previous data is not large enough to display, another set of data is generated here:


np.random.seed (13)

Y = np.random.randint(20, 150, 360) df2 = pd.DataFrame( {'Manufacturer number': ['001', '001', '001' , '002', '002', '002', '003', '003', '003', '004', '004', '004'] * 30,

'Product type': [' AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC'] * 30,
'XXX attribute value': Y

} )


After generation, start drawing the box plot:

##plt.rcParams['font.sans-serif'] = ['STKAITI'] sns.boxplot(x='product type', y='XXX attribute value', data=df2)
plt.show()

ˆ ˆ ˆ ˆDetailed explanation of Pythons Seaborn (data visualization)


After exchanging x and y-axis data: ˆ

plt.rcParams[' font.sans-serif'] = ['STKAITI'] sns.boxplot(y='product type', x='XXX attribute value', data=df2)
plt.show()

You can see that the direction of the box plot has also changed

     Detailed explanation of Pythons Seaborn (data visualization)


Use the manufacturer number as a classification field:

##plt.rcParams['font.sans-serif'] = ['STKAITI']

sns.boxplot (x='product type', y='XXX attribute value', data=df2, hue="manufacturer number") plt.show()

##           

Detailed explanation of Pythons Seaborn (data visualization)11. Draw a violin plot violinplot()


The violin plot combines the features of box plots and kernel density plots to display the distribution shape of the data.

Use the violinplot() method to draw a violin plot.


plt.rcParams['font.sans-serif'] = ['STKAITI']
sns.violinplot(x='Product Type', y=' The ['font.sans-serif'] = ['STKAITI']

sns.violinplot(x='XXX attribute value', y='product type', data=df2) plt.show()

ˆ ˆ ˆ ˆ ˆ

Detailed explanation of Pythons Seaborn (data visualization)


#plt.rcParams['font.sans-serif'] = ['STKAITI']
sns.violinplot(x='product type', y='XXX attribute value', data=df2, hue="manufacturer number")

plt.show()

Detailed explanation of Pythons Seaborn (data visualization)

12. Draw a heat map heatmap()

Take the Shuangseqiu winning number data as an example to draw a heat map. The data here is random. Number generation.

import pandas as pd

import matplotlib.pyplot as pltDetailed explanation of Pythons Seaborn (data visualization) import seaborn as sns

  
sns.set()

plt .figure(figsize=(6,6)) plt.rcParams['font.sans-serif'] = ['STKAITI']  

s1 = np.random.randint(0, 200, 33)

s2 = np.random.randint(0, 200, 33) s3 = np.random.randint(0, 200, 33) s4 = np.random.randint(0, 200 , 33)

s5 = np.random.randint(0, 200, 33)
s6 = np.random.randint(0, 200, 33)

s7 = np.random.randint(0, 200, 33) data = pd.DataFrame(
{'一': s1,
'二': s2,
'三': s3,
'四':s4,
'五':s5,
'六':s6,
'七':s7
}
)

plt.title('Double Color Ball Heat Map')
sns.heatmap(data, annot=True, fmt='d', lw=0.5)
plt.xlabel('Winning Number Digits')
plt.ylabel('Double Color Ball Number')
x = ['1st position', '2nd position', '3rd position', '4th position', '5th position', '6th position', '7th position']
plt.xticks(range(0, 7, 1), x, ha='left')
plt.show()



##       



Recommended learning:
python video tutorial

The above is the detailed content of Detailed explanation of Python's Seaborn (data visualization). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!