Создание связей между тепловыми картами imshow с использованием ConnectionPatch - PullRequest
0 голосов
/ 18 марта 2019

Я пытаюсь создать связи между двумя тепловыми картами, сгенерированными с помощью imshow (dataframe) с помощью ConnectionPatch. Проблема в том, что я хочу использовать индексы данных как коннекторы [xy], но не могу найти никакого способа сделать это. Ниже мой пример набора данных:

# Creating first dataframe
df = pd.DataFrame(
    np.random.randint(0, 100, size=(100, 5)),
    columns=["heatMap_1", "heatMap_2", "heatMap_3", "heatMap_4", "heatMap_5"],
)

df["index"] = [
    "".join(
        random.choice(
            string.ascii_uppercase + string.ascii_lowercase + string.digits
        )
        for _ in range(5)
    )
    for k in df.index
]

df.set_index("index", inplace=True)

df.head()

# Creating the 2nd dataframe
df2 = pd.DataFrame(
    np.random.randint(0, 25, size=(25, 4)),
    columns=["heatMap_1", "heatMap_2", "heatMap_3", "heatMap_4"],
)

df2["index"] = random.sample(list(clusteredDataframe.index.values), 25)
df2.set_index("index", inplace=True)
df2.head()

# Creating heatmaps using imshow and using gridspec
# to arrange them
fig = plt.figure(figsize=(12, 12))
gs = GridSpec(3, 4)
ax_heatmap1 = plt.subplot(gs[0:3, :2])
ax_connect = plt.subplot(gs[0:3, 2:3])
ax_heatmap2 = plt.subplot(gs[1:2, 3:])

im = ax_heatmap1.imshow(df, cmap="inferno", interpolation="None", aspect="auto")

im = ax_heatmap2.imshow(
    df2, cmap="inferno", interpolation="None", aspect="auto"
)

ax_connect - это ось, где я хотел бы, чтобы мои связи были. Я предполагаю, что ConnectionPatch - самый чистый способ сделать это? Или есть лучший подход для этого?

По сути, это то, что я хочу: enter image description here

1 Ответ

1 голос
/ 18 марта 2019

Вы действительно можете использовать ConnectionPatch, чтобы нарисовать линию от всех индексов правой тепловой карты до соответствующих индексов левой.

import numpy as np; np.random.seed(8)
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.patches import ConnectionPatch
import string

n1 = 20
n2 = 5
# Creating first dataframe
df = pd.DataFrame(
    np.random.randint(0, 100, size=(n1, 5)),
    columns=["heatMap_1", "heatMap_2", "heatMap_3", "heatMap_4", "heatMap_5"],
)

chars = list(string.ascii_uppercase + string.ascii_lowercase + string.digits)
df["index"] = ["".join(np.random.choice(chars, size=5)) for k in df.index]

df.set_index("index", inplace=True)


# Creating the 2nd dataframe
df2 = pd.DataFrame(
    np.random.randint(0, 25, size=(n2, 4)),
    columns=["heatMap_1", "heatMap_2", "heatMap_3", "heatMap_4"],
)

df2["index"] = np.random.choice(list(df.index.values), n2)
df2.set_index("index", inplace=True)


# Creating heatmaps using imshow and using gridspec
# to arrange them
fig = plt.figure(figsize=(12,8))
gs = GridSpec(3, 4)
ax_heatmap1 = plt.subplot(gs[0:3, :2])
ax_heatmap2 = plt.subplot(gs[1:2, 3:])

im = ax_heatmap1.imshow(df, cmap="inferno", interpolation="None", aspect="auto")
ax_heatmap1.set(yticks=np.arange(len(df)), yticklabels=df.index.values)
im = ax_heatmap2.imshow(
    df2, cmap="inferno", interpolation="None", aspect="auto")
ax_heatmap2.set(yticks=np.arange(len(df2)), yticklabels=df2.index.values)
# Connect heatmaps by index
ind_list =  list(df.index.values)
x1 = len(df.columns) - 0.5
x2 = -0.5
for i, ind in enumerate(df2.index):
    j = ind_list.index(ind)
    cp = ConnectionPatch((x2, i), (x1, j),  coordsA="data",  coordsB="data",
                          axesA=ax_heatmap2, axesB=ax_heatmap1, color="red", clip_on=False)
    ax_heatmap2.add_artist(cp)

plt.show()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...