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

Data visualization

Data visualization

Before starting to build a complex machine learning model, the first thing we should do is not to choose an algorithm, but tounderstand the data。

If machine learning is compared to cooking, then data is the ingredients.

An excellent chef must understand the characteristics of the ingredients — whether they are fresh or spoiled, sweet or sour, suitable for stewing or quick stir-frying.

Data visualization is the way we observe and taste this ingredient called data — themagnifying glassandand taste buds。

Through visual elements such as charts and graphs, data visualization transforms dull numbers into intuitive images, helping us to:

This article will use the most popular data science library in Python, pandas and the visualization library matplotlib、seabornto help you master the core skills of data visualization.


Preparation: Environment and Data

Before starting to draw, we need to prepare the "canvas" and "paint".

Install necessary libraries

If you are using Anaconda, these libraries are usually pre-installed. Otherwise, you can install them with the following commands:



pip install pandas matplotlib seaborn

Import Libraries and Load Data

We will use a classic public dataset: the Titanic passenger dataset. It contains information about passengers' survival, class, age, gender, and so on.

Example

Import the necessary libraries

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

import

seaborn

as

sns

Set the chart style to make the charts look better

sns.

set_style

(

"whitegrid"

)

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

Load data

Here we load directly from seaborn's built-in datasets

df

=

sns.

load_dataset

(

'titanic'

)

View the first few rows and basic information of the data

print

(

"Data shape (rows, columns):"

,

df.

shape

)

print

(

"\nFirst 5 rows of data:"

)

print

(

df.

head

(

)

)

print

(

"\nBasic data information (types, non-null counts, etc.):"

)

print

(

df.

info

(

)

)

Load data

Here we load directly from seaborn's built-in datasets

df

=

sns.

load_dataset

(

'titanic'

)

View the first few rows and basic information of the data

print

(

"Data shape (rows, columns):"

,

df.

shape

)

print

(

"\nFirst 5 rows of data:"

)

print

(

df.

head

(

)

)

print

(

"\nBasic data information (types, non-null counts, etc.):"

)

print

(

df.

info

(

)

)

Running the code above, you will see that the data has 891 rows (passengers) and 15 columns (features).df.head() gives you a preliminary impression of what the data looks like.


Univariate Analysis: Understanding the Distribution of a Single Feature

Univariate analysis focuses onAthe distribution of a single feature (variable). This is the most basic type of analysis.

1. Numeric Features: Histograms and Box Plots

For continuous numeric features such as age(Age),fare(Fare), we often useHistogramandBoxplot。

Histogramwhich shows the frequency distribution of the data in different intervals ("bins").

Example

Import the necessary libraries

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

import

seaborn

as

sns

Set the chart style to make the charts look better

sns.

set_style

(

"whitegrid"

)

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

Load data

Here we load directly from seaborn's built-in datasets

df

=

sns.

load_dataset

(

'titanic'

)

View the first few rows and basic information of the data

print

(

"Data shape (rows, columns):"

,

df.

shape

)

print

(

"\nFirst 5 rows of data:"

)

print

(

df.

head

(

)

)

print

(

"\nBasic data information (types, non-null counts, etc.):"

)

print

(

df.

info

(

)

)

Draw a histogram of age

plt.

figure

(

figsize

=

(

10

,

6

)

)

Set the chart size

plt.

hist

(

df

[

'age'

]

.

dropna

(

)

,

bins

=

30

,

edgecolor

=

'black'

,

alpha

=

0.7

)

dropna() ignores missing values

plt.

title

(

'Histogram of Passenger Age Distribution'

)

plt.

xlabel

(

'Age'

)

plt.

ylabel

(

'Frequency'

)

plt.

show

(

)

Interpretation: This chart tells us which range passenger ages are mainly concentrated in (for example, 20-30 years old), whether the distribution is symmetric, and whether there are outliers.

Boxplotcan clearly show the data'smedian, quartiles, and outliers。

Example

Draw a box plot of fare

plt.

figure

(

figsize

=

(

8

,

5

)

)

plt.

boxplot

(

df

[

'fare'

]

.

dropna

(

)

)

plt.

title

(

'Fare Box Plot'

)

plt.

ylabel

(

'Fare'

)

plt.

show

(

)

Interpretation: The line in the middle of the box is the median. The upper and lower boundaries of the box are the upper quartile (Q3) and lower quartile (Q1). The upper and lower "whiskers" usually extend to the farthest data point within 1.5 times the interquartile range; points beyond that are consideredOutliers(the circles above the chart). This chart immediately tells us that there are many extremely high outliers in the fares.

2. Categorical Features: Bar Charts

For continuous numeric features such as sex(Gender),embarked(Port of Embarkation),survived(Survival) — for such categorical features, we useBar chartto count the number of each category.

Example

Draw a bar chart of passenger gender

survival_counts

=

df

[

'sex'

]

.

value_counts

(

)

plt.

figure

(

figsize

=

(

8

,

5

)

)

plt.

bar

(

survival_counts.

index

,

survival_counts.

values

,

color

=

[

'lightblue'

,

'lightcoral'

]

)

plt.

title

(

'Passenger Gender Distribution'

)

plt.

xlabel

(

'Gender'

)

plt.

ylabel

(

'Number of People'

)

plt.

show

(

)


Bivariate Analysis: Exploring Relationships Between Features

Bivariate analysis explorestwothe relationship between two features.

1. Numeric vs Numeric: Scatter Plots

Scatter plots are a powerful tool for studying the correlation between two continuous variables.

Example

Draw a scatter plot of age vs. fare

plt.

figure

(

figsize

=

(

10

,

6

)

)

plt.

scatter

(

df

[

'age'

]

,

df

[

'fare'

]

,

alpha

=

0.5

)

alpha sets the transparency, making it easier to observe point density

plt.

title

(

'Age vs. Fare Scatter Plot'

)

plt.

xlabel

(

'Age'

)

plt.

ylabel

(

'Fare'

)

plt.

show

(

)

2. Categorical vs Numeric: Grouped Box Plots or Violin Plots

We often want to know how the distribution of a numeric feature differs across categories. For example: "How does the fare distribution differ among passengers in different classes?"

Example

Draw a grouped box plot using seaborn (pclass: passenger class, 1st/2nd/3rd class)

plt.

figure

(

figsize

=

(

10

,

6

)

)

sns.

boxplot

(

x

=

'pclass'

,

y

=

'fare'

,

data

=

df

)

plt.

title

(

'Fare Distribution by Passenger Class'

)

plt.

show

(

)

Violin Plotis an advanced version of the box plot; it shows not only statistical measures but also the actual distribution shape of the data through kernel density estimation.

Example

Draw a violin plot of the age distribution by gender

plt.

figure

(

figsize

=

(

10

,

6

)

)

sns.

violinplot

(

x

=

'sex'

,

y

=

'age'

,

data

=

df

,

inner

=

'quartile'

)

The inner parameter displays the quartile lines

plt.

title

(

'Age Distribution by Gender (Violin Plot)'

)

plt.

show

(

)

3. Categorical vs Categorical: Stacked Bar Charts or Heatmaps

For two categorical variables, we can usestacked bar chartsto observe the combined situation. For example: "What are the survival rates for different genders?"

Example

Create a cross-tabulation of gender and survival status

cross_tab

=

pd.

crosstab

(

df

[

'sex'

]

,

df

[

'survived'

]

,

normalize

=

'index'

)

normalize='index' calculates proportions by row

print

(

cross_tab

)

Draw a stacked bar chart

cross_tab.

plot

(

kind

=

'bar'

,

stacked

=

True

,

figsize

=

(

10

,

6

)

,

color

=

[

'tomato'

,

'lightgreen'

]

)

plt.

title

(

'Survival Proportion by Gender'

)

plt.

xlabel

(

'Gender'

)

plt.

ylabel

(

'Proportion'

)

plt.

legend

(

[

'Did Not Survive'

,

'Survived'

]

)

plt.

show

(

)

Interpretation: From the chart and cross-tabulation, it is clear that the survival rate of women is much higher than that of men. This is a very strong signal, indicating that sex the feature is crucial for predicting survival.


Multivariate Analysis and Advanced Visualization

Sometimes we need to consider three or even more variables simultaneously.seaborn library makes this easy.

1. Scatter Plots with Grouping

We can build on the scatter plot and use color or shape to distinguish a third (categorical) variable.

Example

In the age-vs-fare scatter plot, use color to distinguish whether a passenger survived

plt.

figure

(

figsize

=

(

12

,

8

)

)

sns.

scatterplot

(

x

=

'age'

,

y

=

'fare'

,

hue

=

'survived'

,

style

=

'survived'

,

data

=

df

,

alpha

=

0.7

)

plt.

title

(

'Age vs Fare (Colored by Survival)'

)

plt.

show

(

)

2. Correlation Matrix Heatmap

When we have multiple numeric features, we can compute the correlation coefficients between every pair of them at once and display them in a heatmap.

Example

Select numeric columns

numeric_df

=

df.

select_dtypes

(

include

=

[

'float64'

,

'int64'

]

)

Compute the correlation coefficient matrix

corr_matrix

=

numeric_df.

corr

(

)

Draw a heatmap

plt.

figure

(

figsize

=

(

12

,

8

)

)

sns.

heatmap

(

corr_matrix

,

annot

=

True

,

cmap

=

'coolwarm'

,

center

=

0

,

square

=

True

)

plt.

title

(

'Numeric Feature Correlation Matrix Heatmap'

)

plt.

show

(

)

Interpretation: Warmer colors (red) indicate a stronger positive correlation; cooler colors (blue) indicate a stronger negative correlation.annot=True Display the specific values inside the cells. For example,pclass(Pclass) and fare(Fare) have a strong negative correlation (-0.55), meaning the smaller the class number (the higher the class), the higher the fare, which is consistent with our earlier analysis.


Hands-on Practice: Explore on Your Own

Now, try to complete the following exercises to reinforce what you have learned:

  1. Data Check: When using df.isnull().sum() Check which columns in the dataset have missing values and how many are missing.
  2. Plot Distributions: For the age column, plot aViolin Plot, and group by survived(survival status) for grouping (using sns.violinplot(x='survived', y='age', data=df)). Observe how the age distributions of survivors and non-survivors differ.
  3. Explore Relationships: When using sns.countplot(x='pclass', hue='survived', data=df) Plot a count bar chart to compare the number of survivors across different passenger classes. What conclusions can you draw?
  4. (Challenge) Multivariate Plot: Try plotting aScatter plot matrix, to view at once age、fare、parch(number of parents/children) — the pairwise relationships among these numeric variables. Hint: you can use sns.pairplot(df[['age', 'fare', 'parch', 'survived']], hue='survived')。

Summary

Data visualization is anindispensable exploratory step in the machine learning workflow. Through this article, you have learned:

Core Tools: When using matplotlib Perform basic plotting, use seaborn to create more attractive and informative statistical graphics.

Analytical Approaches:

Core goal: All charts are meant toformulate hypothesesandand discover insights— for example, gender may be an important predictive feature, and the fare data contains many outliers that need to be handled.

Remember, before feeding data into a model, be sure to take the time to look at it carefully. A clear finding from visualization can often guide you toward the right direction earlier than a complex algorithm can.

Linux Command Reference Linux Command Reference