Pandas and Matplotlib / Seaborn Advanced Visualization
Pandas has built-in basic plotting functionality, and by combining it with Matplotlib and Seaborn, you can create richer visualization charts.
Pandas Built-in Plotting
Line Chart
Example
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Enable Chinese display (requires a Chinese font installed in 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 + np.random.randn(30).cumsum(),
"Visitors": 50 + np.random.randn(30).cumsum() * 10
})
df = df.set_index("Date")
print("Data:")
print(df.head())
print("\n"Plot data preparation complete, please use plt.show() to display the chart")
import numpy as np
import matplotlib.pyplot as plt
# Enable Chinese display (requires a Chinese font installed in 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 + np.random.randn(30).cumsum(),
"Visitors": 50 + np.random.randn(30).cumsum() * 10
})
df = df.set_index("Date")
print("Data:")
print(df.head())
print("\n"Plot 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"],
"Units Sold": [120, 150, 90, 180, 110]
}
df = pd.DataFrame(data)
# Bar chart
print("Use df.plot.bar() to draw a bar chart")
print("\n"Data:")
print(df)
import matplotlib.pyplot as plt
# Categorical data
data = {
"Product": ["A", "B", "C", "D", "E"],
"Units Sold": [120, 150, 90, 180, 110]
}
df = pd.DataFrame(data)
# Bar chart
print("Use df.plot.bar() to draw a bar chart")
print("\n"Data:")
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("\n"Data:")
print(s)
# 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("\n"Data:")
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 plot
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()
""")
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 plot
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()
""")
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()
""")
Seaborn Advanced 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 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()
""")
import numpy as np
# Demonstrate Seaborn features
print("Seaborn visualization example:")
print("""
import seaborn as sns
import matplotlib.pyplot as plt
# Set 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()
""")
Other ExtensionsMatplotlib provides low-level control, while Seaborn provides a high-level interface. Combining the two lets you create a variety of professional charts.