Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Quantitative Data Visualization

Python Quantitative Data Visualization

Python quantitative data visualization mainly uses two libraries: Matplotlib and Seaborn.

Installation can be done by running in a terminal or command prompt:



pip install matplotlib seaborn

For systematic usage of Matplotlib, refer to:Matplotlib Tutorial.

This article focuses on the application of Seaborn in quantitative data analysis.


The Seaborn library

Seaborn is a data visualization library based on Matplotlib, focused on drawing statistical graphics.

It provides a higher-level interface and more attractive default themes on top of Matplotlib, producing better-looking statistical charts with less code.

Quickly drawing statistical graphics

Seaborn includes a set of classic datasets; combined with its built-in plotting functions, a single line of code can draw statistical graphics:

Example

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

Load the built-in tips dataset (restaurant tip data)

tips

=

sns.

load_dataset

(

"tips"

)

Draw a scatter plot of bill amount vs. tip, colored by meal time

sns.

scatterplot

(

x

=

"total_bill"

,

y

=

"tip"

,

hue

=

"time"

,

data

=

tips

)

plt.

title

(

"Total Bill vs Tip"

)

plt.

show

(

)

The function name is the chart type: scatterplot for scatter plots, lineplot for line charts, barplot for bar charts, histplot for histograms, which is very friendly for beginners.

Themes and styles

Seaborn provides built-in themes; a single line of code changes the chart's appearance:

Example

import

seaborn

as

sns

Use the white grid theme; darkgrid, white, dark, and ticks are also available

sns.

set

(

style

=

"whitegrid"

)

Visualization of categorical data

For data with categorical dimensions, Seaborn can easily create grouped bar charts, box plots, and more:

Example

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

tips

=

sns.

load_dataset

(

"tips"

)

Draw a bar chart of bill amount grouped by day of week; the hue parameter further splits by gender

sns.

barplot

(

x

=

"day"

,

y

=

"total_bill"

,

hue

=

"sex"

,

data

=

tips

)

plt.

title

(

"Average Bill by Day and Gender"

)

plt.

show

(

)

Visualization of matrix data

Seaborn provides functions specifically for visualizing matrix data; the most commonly used is the heatmap, often used in quantitative analysis to display correlation matrices:

Example

import

numpy

as

np

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

Generate a 5x5 random matrix

matrix

=

np.

random

.

rand

(

5

,

5

)

Draw a heatmap; annot=True displays the values inside each cell

sns.

heatmap

(

matrix

,

annot

=

True

,

cmap

=

"coolwarm"

)

plt.

show

(

)

Faceted plotting

Faceted plotting creates multiple small charts based on subsets of the data, fully showing how the data behaves across different dimensions:

Example

import

seaborn

as

sns

tips

=

sns.

load_dataset

(

"tips"

)

col="time" splits into two side-by-side subplots by meal time

sns.

relplot

(

x

=

"total_bill"

,

y

=

"tip"

,

hue

=

"day"

,

col

=

"time"

,

data

=

tips

)


Quantitative example: stock price trend chart

Entering quantitative scenarios, combined with yfinance Fetch stock data for Kweichow Moutai (600519.SS), then use Seaborn to plot the closing price trend:

Example

import

yfinance

as

yf

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

Fetch stock data for Kweichow Moutai

maotai_data

=

yf.

download

(

"600519.SS"

,

start

=

"2020-01-01"

,

end

=

"2023-01-01"

,

                          progress

=

False

,

multi_level_index

=

False

)

Select the closing price data

closing_prices

=

maotai_data

[

"Close"

]

Use seaborn to draw the trend chart

plt.

figure

(

figsize

=

(

12

,

6

)

)

sns.

lineplot

(

x

=

closing_prices.

index

,

y

=

closing_prices.

values

,

             label

=

"Maotai Closing Prices"

)

plt.

title

(

"Maotai Stock Closing Prices Over Time"

)

plt.

xlabel

(

"Date"

)

plt.

ylabel

(

"Closing Price (CNY)"

)

plt.

legend

(

)

plt.

show

(

)

The output of the code above is:

Compared with using Matplotlib directly, Seaborn's default color palette and grid give the chart noticeably better quality, with almost the same amount of code.


Quantitative example: multi-stock correlation heatmap

Correlation analysis is the starting point of portfolio research: if two stocks rise and fall in high sync, holding both at the same time does not diversify risk.

The following example computes the correlation between daily returns of three leading liquor-sector stocks (Kweichow Moutai, Wuliangye, Luzhou Laojiao) and displays it with a heatmap:

Example

import

yfinance

as

yf

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

Three leading liquor stocks: Kweichow Moutai, Wuliangye, Luzhou Laojiao

symbols

=

[

"600519.SS"

,

"000858.SZ"

,

"000568.SZ"

]

Download the full-year closing prices for 2023

close

=

yf.

download

(

symbols

,

start

=

"2023-01-01"

,

end

=

"2023-12-31"

,

                    progress

=

False

,

multi_level_index

=

False

)

[

"Close"

]

Compute daily returns, then compute the correlation matrix

corr

=

close.

pct_change

(

)

.

corr

(

)

print

(

corr.

round

(

3

)

)

Draw the correlation heatmap

plt.

figure

(

figsize

=

(

8

,

6

)

)

sns.

heatmap

(

corr

,

annot

=

True

,

cmap

=

"coolwarm"

,

vmin

=

1

,

vmax

=

1

,

square

=

True

)

plt.

title

(

"Correlation of Daily Returns (Baijiu Stocks 2023)"

)

plt.

show

(

)

First look at the output correlation matrix:



Ticker     000568.SZ  000858.SZ  600519.SS

Ticker

000568.SZ      1.000      0.842      0.773

000858.SZ      0.842      1.000      0.770

600519.SS      0.773      0.770      1.000

The pairwise correlations among the three stocks range from 0.77 to 0.84, which is considered highly correlated.

This shows that stocks in the same industry tend to rise and fall together; when building a portfolio you should avoid over-concentrating funds in a single industry, otherwise 'diversification' is only nominal.

After running the code a heatmap will also pop up, as shown below (the redder the color, the stronger the correlation):

Luzhou Laojiao Wuliangye Kweichow Moutai Luzhou Laojiao Wuliangye Kweichow Moutai 1.00 0.84 0.77 0.84 1.00 0.77 0.77 0.77 1.00 -1 0 +1

Note: vmin=-1, vmax=1 fixes the color bar range to the theoretical interval of correlation, allowing direct comparison between different charts; without this parameter, the color bar range automatically scales with the data.


Selection recommendations

Matplotlib and Seaborn are not an either-or choice; in practice they are usually used together:

Scenario Recommended tool
Quick data exploration, statistical charts Seaborn, less code and good default styles
Fine control over every detail of the chart Matplotlib, the highest degree of freedom
Quantitative-specific charts (candlestick/K-line charts, etc.) Requires specialized libraries, see Stock K-line chart
Interactive web charts pyecharts, Plotly