包含横向柱状图、雷达图、分簇散点图、分边小提琴图、三维面图和多维信息散点图的绘制代码。其中部分代码块也对配色方法color_palette()LinearSegmentedColormap()的用法进行了展示。

Python
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
import pandas as pd
from pylab import *
from matplotlib.colors import ListedColormap, LinearSegmentedColormap


# 横向柱状图
def barplot_h_diamond():
    df_diamonds = pd.read_csv('seaborn-data/diamonds.csv')
    df_diamonds['cut_counts'] = 1
    # 分组求和
    data = df_diamonds[['cut', 'cut_counts']].groupby('cut').sum().reset_index()
    # 降序排列
    data = data.sort_values('cut_counts', ascending=False)

    plt.figure(figsize=(12, 12))

    # 坐标轴格式
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'

    palette = sns.color_palette(['#306884', '#46966E', '#A0B87B', '#EDB74D', '#D54A38'])
    # 注意,横向柱形图的xy数据格式和纵向相反
    plt.ylabel('Quality')
    plt.xlabel('Counts')
    sns.barplot(y=list(data['cut']), x=list(data['cut_counts']), orient='h', palette=palette)
    plt.show()


# 散点图
def scatter_diamond():
    # 已被多维信息散点图替代
    pass


# 雷达图
def radarplot():
    # 数据准备
    labels = np.array([u'推进', 'KDA', u'生存', u'团战', u'发育', u'输出'])
    stats = [83, 61, 95, 67, 76, 88]
    # 画图数据准备,角度,状态值
    angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False)
    stats = np.concatenate((stats, [stats[0]]))
    angles = np.concatenate((angles, [angles[0]]))
    labels = np.concatenate((labels, [labels[0]]))  # 上述3行:将没有闭合的数据闭合
    # 使用matplotlib作图
    fig = plt.figure()
    ax = fig.add_subplot(111, polar=True)
    ax.plot(angles, stats, 'o-', color='r', linewidth=2)
    ax.fill_between(angles, stats, color='r', alpha=0.25)
    # 设置中文字体
    font = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
    ax.set_thetagrids(angles * 180 / np.pi, labels, fontproperties=font)
    plt.show()


# 分簇散点图
def swarmplot_iris(mode=0):
    if mode == 0:
        iris = pd.read_csv(r'C:\ProgramData\Anaconda3\Lib\site-packages\bokeh\sampledata\_data\iris.csv')

        plt.rcParams['xtick.direction'] = 'in'
        plt.rcParams['ytick.direction'] = 'in'

        f, ax1 = plt.subplots()
        ax2 = ax1.twinx()

        palette_1 = sns.color_palette(["#D54A38"])
        palette_2 = sns.color_palette(["#306884"])
        sns.swarmplot(x='species', y='petal_width', ax=ax1, data=iris, size=3, palette=palette_1)
        sns.swarmplot(x='species', y='petal_length', ax=ax2, data=iris, size=3, palette=palette_2)

        ax1.legend(labels=['petal_width'], loc=2)
        ax2.legend(labels=['petal_length'], loc=4)
        plt.show()
    else:
        df_diamonds = pd.read_csv('seaborn-data/diamonds.csv')
        df_diamonds_ideal = df_diamonds[df_diamonds['cut'] == 'Ideal'].iloc[: 100,]
        df_diamonds_good = df_diamonds[df_diamonds['cut'] == 'Good'].iloc[: 100,]
        df_diamonds = pd.concat([df_diamonds_ideal, df_diamonds_good])

        plt.rcParams['xtick.direction'] = 'in'
        plt.rcParams['ytick.direction'] = 'in'

        palette_spl = sns.color_palette(["#D54A38", "#306884"])

        sns.swarmplot(x='color', y='carat', hue='cut', data=df_diamonds, palette=palette_spl)
        plt.show()


# 分边小提琴图
def violinplot_diamond():
    df_diamonds = pd.read_csv('seaborn-data/diamonds.csv')

    df_diamonds = df_diamonds[(df_diamonds['cut'] == 'Ideal') | (df_diamonds['cut'] == 'Good')]

    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'

    palette_spl = sns.color_palette(["#D54A38", "#306884"])

    sns.violinplot(x='color', y='price', hue='cut', data=df_diamonds, split=True, palette=palette_spl, linewidth=1)
    plt.show()


# 三维面图
def tri_surface_diamond():

    # 自定义colormap
    c_list = ["#A63130", "#D54A38", "#EDB74D", "#000000", "#A0B87B", "#46966E", "#306884", "#7D7D7D"]
    new_cmap = LinearSegmentedColormap.from_list('sci_standard', c_list)

    df_diamonds = pd.read_csv('seaborn-data/diamonds.csv')
    df_diamonds = df_diamonds[df_diamonds['cut'] == 'Ideal']

    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'

    X = np.array(df_diamonds['price'])
    Y = np.array(df_diamonds['depth'])
    Z = np.array(df_diamonds['table'])

    ax = plt.axes(projection='3d')
    ax.plot_trisurf(X, Y, Z, cmap=new_cmap)
    plt.show()


# 多维信息散点图
def scatter_pro_diamond():
    df_diamonds = pd.read_csv('seaborn-data/diamonds.csv')

    # 配色方案1:层析
    palette_1 = sns.color_palette(
        ["#A63130", "#D54A38", "#EDB74D", "#000000", "#A0B87B", "#46966E", "#306884", "#7D7D7D"])

    # 配色方案2:渐变
    palette_2 = sns.color_palette(palette='blend:#A63130,#306884', n_colors=8)

    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    f, ax = plt.subplots(figsize=(8, 6))

    # 设置xy轴范围和刻度间距
    ax.set_xlim(0, 5)
    ax.set_xticks(range(0, 6))
    ax.set_ylim(1, 20000)  # 避免出现两个零刻度

    clarity_ranking = ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"]
    # hue可以将变量和颜色绑定,size可以将变量和点半径绑定,二者可以独立存在,也可以共同作用于同一变量
    sns.scatterplot(x="carat", y="price",
                    hue="clarity", size="depth",
                    palette=palette_2,
                    hue_order=clarity_ranking,
                    sizes=(1, 8), linewidth=0,
                    data=df_diamonds, ax=ax)
    plt.show()


if __name__ == '__main__':
    barplot_h_diamond()  # 横向柱状图
    # scatter_pro_diamond()  # 多维散点图
    # radarplot()  # 雷达图
    # swarmplot_iris(mode=1)  # 分簇散点图
    # violinplot_diamond()  # 分边小提琴图
    # tri_surface_diamond()  # 三维面图