【问题标题】:Plot Colorbar for stripplot为条形图绘制颜色条
【发布时间】:2019-03-23 01:54:34
【问题描述】:

我有一个带状图,我在其中使用分箱数据为数据点着色。我想显示一个彩条,而不是图例。我看过很多例子,但我一直不知道如何将它与 Seaborn Stripplot(和我的数据集)一起使用。

我有一个数据框 dfBalance,它在 Balance 列中有数字数据,在 Parameter 列中有不同的类别。它还包含时间列中的时间,我用它来为数据点着色

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame([[40, 'A',65], [-10, 'A',125], [60, 'B',65], [5, 'B',135], [8, 'B',205], [14, 'B',335]], columns=['Balance', 'Parameter', 'Time'])

bin = np.arange(0,max(df['Time']),60)
df['bin'] = pd.cut(abs(df['Time']),bin,precision=0)

plt.figure()
cpal=sns.color_palette('cmo.balance',n_colors=28,desat=0.8)
plt.style.use("seaborn-dark")
ax = sns.stripplot(x='Balance', y='Parameter', data=df, jitter=0.15, edgecolor='none', alpha=0.4, size=4, hue='bin', palette=cpal)
sns.despine()
ax.set_xlim([-45,45])
plt.title("L/R Balance")
plt.xlabel("Balance % L/R")
plt.ylabel("Parameter")
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
plt.legend(loc=1)

plt.show()

这会产生如下图:

有没有办法用颜色条代替图例?

【问题讨论】:

标签: python matplotlib seaborn colorbar


【解决方案1】:

最后,我认为解决方案应该与the one proposed in this recent question完全相同,并且当前问题可以/应该标记为重复。

我不得不稍微修改一下你的代码,因为我看不清这些要点,但希望不会有太大的不同。

from matplotlib.cm import ScalarMappable

df = pd.DataFrame({'Balance': np.random.normal(loc=0, scale=40, size=(1000,)),
                   'Parameter': [['A','B'][i] for i in np.random.randint(0,2, size=(1000,))],
                   'Time': np.random.uniform(low=0, high=301, size=(1000,))})

bin = np.arange(0,max(df['Time']),60)
df['bin'] = pd.cut(abs(df['Time']),bin,precision=0)

plt.figure()
cpal=sns.color_palette('Spectral',n_colors=5,desat=1.)
plt.style.use("seaborn-dark")
ax = sns.stripplot(x='Balance', y='Parameter', data=df, jitter=0.15, edgecolor='none', alpha=0.4, size=4, hue='bin', palette=cpal)
sns.despine()
ax.set_xlim([-45,45])
plt.title("L/R Balance")
plt.xlabel("Balance % L/R")
plt.ylabel("Parameter")
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})

# This is the part about the colormap
cmap = plt.get_cmap("Spectral")
norm = plt.Normalize(0, df['Time'].max())
sm =  ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([])
cbar = fig.colorbar(sm, ax=ax)
cbar.ax.set_title("\"bins\"")

#remove the legend created by seaborn
ax.legend_.remove()

plt.show()

【讨论】:

    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多