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

Advanced Visualization with Pandas and Matplotlib / Seaborn

Advanced Visualization with Pandas and Matplotlib / Seaborn

Pandas has built-in basic plotting capabilities; combined with Matplotlib and Seaborn, you can create richer visualizations.


Pandas built-in plotting

Line chart

Example

import

pandas

as

pd

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

Configure Chinese font display (requires a Chinese font installed on the system)

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

plt.rcParams['axes.unicode_minus'] = False

Create time series data

dates

=

pd.

date_range

(

"2024-01-01"

,

periods

=

30

,

freq

=

"D"

)

df

=

pd.

DataFrame

(

{

   

"date"

: dates

,

   

"Sales"

:

100

random

.

randn

(

30

)

.

cumsum

(

)

,

   

"Number of visitors"

:

50

random

.

randn

(

30

)

.

cumsum

(

)

10

}

)

df

=

df.

set_index

(

"date"

)

print

(

"Data:"

)

print

(

df.

head

(

)

)

print

(

"\nPlot data preparation complete; please use plt.show() to display the chart"

)

Bar chart

Example

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

Categorical data

data

=

{

   

"Product"

:

[

"A"

,

"B"

,

"C"

,

"D"

,

"E"

]

,

   

"Sales"

:

[

120

,

150

,

90

,

180

,

110

]

}

df

=

pd.

DataFrame

(

data

)

Bar chart

print

(

"Use df.plot.bar() to draw a bar chart"

)

print

(

"\nData:"

)

print

(

df

)

Pie chart

Example

import

pandas

as

pd

Pie chart data

s

=

pd.

Series

(

[

30

,

25

,

20

,

15

,

10

]

,

index

=

[

"A"

,

"B"

,

"C"

,

"D"

,

"E"

]

)

print

(

"Use s.plot.pie() to draw a pie chart"

)

print

(

"\nData:"

)

print

(

s

)


Combining with Matplotlib

Example

import

pandas

as

pd

import

numpy

as

np

Create data

df

=

pd.

DataFrame

(

{

   

"x"

:

range

(

10

)

,

   

"y1"

: np.

random

.

randn

(

10

)

.

cumsum

(

)

,

   

"y2"

: np.

random

.

randn

(

10

)

.

cumsum

(

)

5

}

)

print

(

"Matplotlib plotting example code:"

)

print

(

"""
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))

Line chart

ax1.plot(df["x"], df["y1"], label="Y1", color="blue")
ax1.plot(df["x"], df["y2"], label="Y2", color="red")
ax1.set_title("Line Chart")
ax1.legend()
ax1.grid(True)

Scatter chart

ax2.scatter(df["y1"], df["y2"], alpha=0.6)
ax2.set_title("Scatter Plot")
ax2.set_xlabel("Y1")
ax2.set_ylabel("Y2")

plt.tight_layout()
plt.show()
"""

)

Subplot layout

Example

import

pandas

as

pd

import

numpy

as

np

2x2 subplot example

print

(

"2x2 subplot layout example:"

)

print

(

"""
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

1. Line chart

df["y1"].plot(ax=axes[0, 0])
axes[0, 0].set_title("Line Chart")

2. Bar chart

df["y2"].plot.bar(ax=axes[0, 1])
axes[0, 1].set_title("Bar Chart")

3. Histogram

df["y1"].hist(ax=axes[1, 0], bins=10)
axes[1, 0].set_title("Histogram")

4. Pie chart

pd.Series([10, 20, 30]).plot.pie(ax=axes[1, 1])
axes[1, 1].set_title("Pie Chart")

plt.tight_layout()
plt.show()
"""

)


Advanced Seaborn visualization

Example

import

pandas

as

pd

import

numpy

as

np

Demonstrate Seaborn features

print

(

"Seaborn visualization example:"

)

print

(

"""
import seaborn as sns
import matplotlib.pyplot as plt

Set the style

sns.set_style("whitegrid")

1. Relational plot

fig, ax = plt.subplots(figsize=(8, 5))
sns.lineplot(data=df, x="x", y="y1", ax=ax)
ax.set_title("Line Chart")

2. Distribution plot

sns.histplot(df["y1"], kde=True, ax=ax)

3. Box plot

sns.boxplot(data=df, x="category", y="value")

4. Heatmap

sns.heatmap(df.corr(), annot=True, cmap="coolwarm")

plt.show()
"""

)

Matplotlib provides low-level control, while Seaborn provides a high-level interface; combining the two lets you create all kinds of professional charts.