我可以在 seaborn 和 networkx 之间协调颜色吗?

Ton*_*y B 5 python matplotlib networkx seaborn colormap

我正在尝试将networkx网络图表上的颜色与图表上的颜色进行协调seaborn。当我使用相同的调色板 (Dark2) 和相同的组 ID 时,两个图仍然不同。需要明确的是,第 0 组中的节点应与第 0 组中的条形相同。第 1 组和第 2 组也应如此。这是我运行下面的代码时得到的图表,显示颜色不保持一致: 示例图表

当我运行下面的代码时,在网络图中,组 0 的颜色与计数图中的颜色相同。但是第 1 组和第 2 组会更改网络图和计数图之间的颜色。有谁知道如何协调颜色?

我将颜色映射与plt.cm.Dark2.colors中的映射进行了比较sns.color_palette('Dark2', 3),它们看起来是相同的(除了sns仅包含前 3 种颜色的事实。

另外值得注意的是,seaborn遵循颜色预期顺序networkx不是。

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import seaborn as sns

# create dataframe of connections
df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']})

# create graph
G = nx.Graph()
for i, r in df.iterrows():
    G.add_edge(r['from'], r['to'])

# create data frame mapping nodes to groups
groups_df = pd.DataFrame()

for i in G.nodes():
    if i in 'AD':
        group = 0
    elif i in 'BC':
        group = 1
    else:
        group = 2

    groups_df.loc[i, 'group'] = group

# make sure it's in same order as nodes of graph
groups_df = groups_df.reindex(G.nodes())

# create node node and count chart where color is group id
fig, ax = plt.subplots(ncols=2)
nx.draw(G, with_labels=True, node_color=groups_df['group'], cmap=plt.cm.Dark2, ax=ax[0])

sns.countplot('index', data=groups_df.reset_index(), palette='Dark2', hue='group', ax=ax[1])
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 8

networkx 在颜色图的颜色上平均分配值。由于它显然不能接受norm(这将是解决此问题的常用方法),因此您需要创建一个仅包含您感兴趣的颜色的新颜色图。

cmap = ListedColormap(plt.cm.Dark2(np.arange(3)))
Run Code Online (Sandbox Code Playgroud)

此外,seaborn 会降低要使用的颜色的饱和度,因此要获得与颜色图相同的颜色,您需要saturation=1在 seaborn 调用中进行设置。

import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns

# create dataframe of connections
df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C']})
# create graph
G = nx.Graph()
for i, r in df.iterrows():
    G.add_edge(r['from'], r['to'])

# create data frame mapping nodes to groups
groups_df = pd.DataFrame()

for i in G.nodes():
    if i in 'AD':
        group = 0
    elif i in 'BC':
        group = 1
    else:
        group = 2
    groups_df.loc[i, 'group'] = group

# make sure it's in same order as nodes of graph
groups_df = groups_df.reindex(G.nodes())

# create node node and count chart where color is group id
fig, ax = plt.subplots(ncols=2)

# create new colormap with only the first 3 colors from Dark2
cmap = ListedColormap(plt.cm.Dark2(np.arange(3)))
nx.draw(G, with_labels=True, node_color=groups_df['group'], cmap=cmap, ax=ax[0])

sns.countplot('index', data=groups_df.reset_index(), palette=cmap.colors, hue='group', ax=ax[1], saturation=1)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明