Добавление цветовой полосы на диаграмму рассеяния после цикла - PullRequest
2 голосов
/ 09 июля 2020

Я пытаюсь добавить непрерывную цветовую полосу к диаграмме рассеивания морского дна (аналогично ответам здесь и здесь ). Для моих целей я строю диаграмму рассеяния с помощью al oop, а затем пытаюсь добавить непрерывную цветовую полосу, но я не знаю, какой объект включить в качестве аргумента fig.colorbar(). Как бы вы это сделали?

import pandas as pd
import seaborn as sb
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)

df=pd.DataFrame(np.random.rand(2, 100), index=['S1','S2']).T
tars=np.random.choice([0,0.3,0.5,0.8,1], 100)
df=pd.concat([df,pd.Series(tars, name='group')],1)
colors = matplotlib.cm.viridis(np.linspace(0,1,len(pd.unique(tars))))

fig = plt.figure(figsize = (10,8), dpi=300)
ax = fig.add_subplot(1,1,1) 
targets=pd.unique(tars)
for target, color in zip(targets,colors):
    ...
    g=ax.scatter(
        df.loc[df.group==target, 'S1'], 
        df.loc[df.group==target, 'S2'],
        color = [color]
    )
fig.colorbar(g)
plt.show()

enter image description here

If I add ax.legend(targets) instead of fig.colorbar(g), the legend displays correctly but is categorical.

df=pd.DataFrame(np.random.rand(2, 100), index=['S1','S2']).T
tars=np.random.choice([0,0.3,0.5,0.8,1], 100)
df=pd.concat([df,pd.Series(tars, name='group')],1)

cmap=matplotlib.cm.gnuplot2
colors = cmap(np.linspace(0,1,len(pd.unique(tars))))

fig = plt.figure(figsize = (10,8), dpi=300)
ax = fig.add_subplot(1,1,1) 
targets=pd.unique(tars)
for target, color in zip(targets,colors):
    ...
    g=ax.scatter(
        df.loc[df.group==target, 'S1'], 
        df.loc[df.group==target, 'S2'],
        color = [color]
    )
ax.legend(targets)
plt.show()

введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 10 июля 2020

Спасибо за этот ответ Я смог отредактировать свой код, чтобы отображалась непрерывная цветная полоса.

df=pd.DataFrame(np.random.rand(2, 100), index=['S1','S2']).T
tars=np.random.choice([0,0.3,0.5,0.8,1], 100)
df=pd.concat([df,pd.Series(tars, name='group')],1)

cmap=matplotlib.cm.viridis
colors = cmap(np.linspace(0,1,len(pd.unique(tars))))

fig = plt.figure(figsize = (10,8), dpi=300)
ax = fig.add_subplot(1,1,1) 
targets=pd.unique(tars)
for target, color in zip(targets,colors):
    g=ax.scatter(
        df.loc[df.group==target, 'S1'], 
        df.loc[df.group==target, 'S2'],
        color=[color]
    )

norm = plt.Normalize(np.min(tars), np.max(tars))
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
ax.figure.colorbar(sm)
plt.show()

введите описание изображения здесь

0 голосов
/ 10 июля 2020

Я не совсем уверен, что понимаю, чего вы пытаетесь достичь с помощью for-l oop.

Это тот результат, который вы ищете?

fig = plt.figure()
ax = fig.add_subplot(1,1,1) 
g = ax.scatter(df['S1'],df['S2'],c=df['group'],cmap='viridis')
cbar = fig.colorbar(g)
plt.show()

введите описание изображения здесь

...