Python脚本数据可视化Seaborn风格如何配

wen 实用脚本 2

本文目录导读:

Python脚本数据可视化Seaborn风格如何配

  1. 基础风格设置
  2. 详细配置参数
  3. 完整风格配置示例
  4. 自定义RGB颜色方案
  5. 主题化风格方案
  6. 快速调色板预览
  7. 最佳实践建议

我来详细介绍一下Seaborn的数据可视化风格配置方法。

基础风格设置

预设风格(5种)

import seaborn as sns
import matplotlib.pyplot as plt
# 可用的风格
sns.set_style("whitegrid")    # 白色网格背景
sns.set_style("darkgrid")     # 深色网格背景
sns.set_style("white")        # 白色无网格
sns.set_style("dark")         # 深色无网格
sns.set_style("ticks")        # 带刻度标记

使用示例

import numpy as np
import pandas as pd
# 生成示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 设置风格
sns.set_style("whitegrid")
sns.set_palette("husl")
plt.figure(figsize=(10, 6))
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')'Seaborn Whitegrid Style')
plt.legend()
plt.show()

详细配置参数

上下文设置(影响尺寸和比例)

# 四种上下文
sns.set_context("paper")      # 论文样式,较小
sns.set_context("notebook")   # 笔记本样式(默认)
sns.set_context("talk")       # 演讲样式,较大
sns.set_context("poster")     # 海报样式,最大
# 自定义上下文参数
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})

调色板配置

# 分类调色板
sns.set_palette("deep")       # 深色
sns.set_palette("muted")      # 柔和
sns.set_palette("bright")     # 明亮
sns.set_palette("pastel")     # 粉彩
sns.set_palette("dark")       # 深色
sns.set_palette("colorblind")  # 色盲友好
# 连续调色板
sns.set_palette("viridis")    # 彩虹色
sns.set_palette("rocket")     # 火箭色
sns.set_palette("mako")       # 深蓝到浅蓝
# 自定义调色板
custom_palette = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4"]
sns.set_palette(custom_palette)

完整风格配置示例

专业图表配置

def configure_professional_style():
    """配置专业的图表风格"""
    # 整体风格设置
    sns.set_style("whitegrid", {
        "axes.facecolor": "#FAFAFA",
        "grid.color": "#E8E8E8",
        "grid.linestyle": "--",
        "grid.alpha": 0.7,
    })
    # 上下文设置
    sns.set_context("notebook", {
        "font.size": 12,
        "axes.labelsize": 14,
        "axes.titlesize": 16,
        "xtick.labelsize": 10,
        "ytick.labelsize": 10,
        "legend.fontsize": 10,
        "lines.linewidth": 2,
    })
    # 调色板设置
    sns.set_palette("husl", 8)  # HUSL色彩空间,8个颜色
    # 字体设置
    plt.rcParams['font.family'] = 'Arial'
    plt.rcParams['font.sans-serif'] = ['Arial']

应用完整配置

# 应用配置
configure_professional_style()
# 创建数据
np.random.seed(42)
data = pd.DataFrame({
    'x': range(20),
    'y': np.random.randn(20).cumsum(),
    'group': ['A'] * 10 + ['B'] * 10
})
# 绘制图表
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# 1. 折线图
sns.lineplot(data=data, x='x', y='y', ax=axes[0,0])
axes[0,0].set_title('Line Plot')
# 2. 散点图
sns.scatterplot(data=data, x='x', y='y', hue='group', 
                s=100, ax=axes[0,1])
axes[0,1].set_title('Scatter Plot')
# 3. 箱线图
sns.boxplot(data=data, x='group', y='y', ax=axes[1,0])
axes[1,0].set_title('Box Plot')
# 4. 直方图
sns.histplot(data=data, x='y', bins=15, ax=axes[1,1])
axes[1,1].set_title('Histogram')
plt.tight_layout()
plt.show()

自定义RGB颜色方案

# 公司品牌色方案
CORPORATE_COLORS = {
    'primary': '#2C3E50',      # 深蓝
    'secondary': '#3498DB',    # 亮蓝
    'accent': '#E74C3C',       # 红色
    'info': '#2ECC71',         # 绿色
    'warning': '#F39C12',      # 橙色
    'background': '#FAFAFA',   # 背景色
    'grid': '#ECF0F1',         # 网格色
}
def apply_corporate_style():
    """应用公司品牌配色方案"""
    # 设置整体风格
    sns.set_style("whitegrid", {
        "axes.facecolor": CORPORATE_COLORS['background'],
        "figure.facecolor": 'white',
        "grid.color": CORPORATE_COLORS['grid'],
        "grid.linestyle": "-",
        "grid.alpha": 0.5,
        "axes.edgecolor": CORPORATE_COLORS['primary'],
        "axes.labelcolor": CORPORATE_COLORS['primary'],
        "xtick.color": CORPORATE_COLORS['primary'],
        "ytick.color": CORPORATE_COLORS['primary'],
    })
    # 设置调色板
    brand_palette = [
        CORPORATE_COLORS['primary'],
        CORPORATE_COLORS['secondary'],
        CORPORATE_COLORS['accent'],
        CORPORATE_COLORS['info'],
        CORPORATE_COLORS['warning']
    ]
    sns.set_palette(brand_palette)
    # 字体设置
    plt.rcParams['font.size'] = 12
    plt.rcParams['axes.titlesize'] = 14
    plt.rcParams['axes.labelsize'] = 12
# 应用公司风格
apply_corporate_style()
# 创建示例图表
fig, ax = plt.subplots(figsize=(10, 6))
# 数据
categories = ['Q1', 'Q2', 'Q3', 'Q4']
values = [23, 45, 56, 78]
errors = [2, 3, 4, 3]
# 绘制柱状图
bars = ax.bar(categories, values, yerr=errors, capsize=5)
# 添加数据标签
for bar, val in zip(bars, values):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 1,
            f'{val}', ha='center', va='bottom')
ax.set_title('Quarterly Performance')
ax.set_xlabel('Quarter')
ax.set_ylabel('Values')
plt.tight_layout()
plt.show()

主题化风格方案

# 预设主题包
STYLE_THEMES = {
    "modern": {
        "style": "whitegrid",
        "context": "talk",
        "palette": "viridis",
        "rc_params": {
            "grid.linestyle": "-",
            "grid.alpha": 0.3,
            "axes.edgecolor": "#333333"
        }
    },
    "elegant": {
        "style": "white",
        "context": "notebook",
        "palette": "husl",
        "rc_params": {
            "font.family": "serif",
            "axes.spines.top": False,
            "axes.spines.right": False
        }
    },
    "minimalist": {
        "style": "ticks",
        "context": "paper",
        "palette": "muted",
        "rc_params": {
            "axes.spines.left": True,
            "axes.spines.bottom": True,
            "axes.spines.top": False,
            "axes.spines.right": False,
            "xtick.major.width": 1,
            "ytick.major.width": 1
        }
    },
    "dark": {
        "style": "darkgrid",
        "context": "poster",
        "palette": "magma",
        "rc_params": {
            "figure.facecolor": "#1a1a1a",
            "axes.facecolor": "#2d2d2d",
            "text.color": "#ffffff",
            "axes.labelcolor": "#ffffff",
            "xtick.color": "#ffffff",
            "ytick.color": "#ffffff"
        }
    }
}
def apply_theme(theme_name="modern"):
    """应用预设主题"""
    if theme_name not in STYLE_THEMES:
        raise ValueError(f"Theme {theme_name} not found")
    theme = STYLE_THEMES[theme_name]
    # 应用基本设置
    sns.set_style(theme["style"], theme.get("rc_params", {}))
    sns.set_context(theme["context"])
    sns.set_palette(theme["palette"])
# 使用不同主题
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
for ax, (theme_name, _) in zip(axes.flat, STYLE_THEMES.items()):
    apply_theme(theme_name)
    # 绘制示例数据
    x = np.linspace(0, 10, 100)
    y = np.sin(x) + np.random.randn(100) * 0.1
    ax.plot(x, y, label='Data')
    ax.plot(x, np.sin(x), '--', label='Trend', alpha=0.8)
    ax.set_title(f'{theme_name.capitalize()} Theme')
    ax.legend()
plt.tight_layout()
plt.show()

快速调色板预览

def show_palettes():
    """显示所有调色板"""
    palettes = ['deep', 'muted', 'bright', 'pastel', 'dark', 'colorblind']
    fig, axes = plt.subplots(2, 3, figsize=(15, 8))
    for ax, palette in zip(axes.flat, palettes):
        colors = sns.color_palette(palette, 10)
        sns.palplot(colors, ax=ax)
        ax.set_title(f'Palette: {palette}', fontsize=14)
    plt.tight_layout()
    plt.show()
# 显示所有调色板
show_palettes()

最佳实践建议

  1. 保持一致性:在同一个报告或项目中保持相同的风格配置
  2. 考虑受众:正式报告用专业风格,演讲用醒目风格
  3. 色盲友好:重要图表使用'colorblind'调色板
  4. 文件导出:使用 plt.savefig('figure.png', dpi=300, bbox_inches='tight')

这些配置方法可以帮助你快速调整图表的视觉效果,创建专业、美观的数据可视化图表。

抱歉,评论功能暂时关闭!