python - 如何跨不同类型的 Seaborne/Matplotlib 子图同步颜色

标签 python pandas matplotlib colors seaborn

我正在尝试创建一个包含两个地 block 的子图。第一个图本质上是散点图(我使用的是 regplot),第二个是直方图。

我的代码如下:

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

data = {'source':['B1','B1','B1','C2','C2','C2'],
        'depth':[1,4,9,1,3,10],
        'value':[10,4,23,78,24,45]}

df = pd.DataFrame(data)

f, (ax1, ax2) = plt.subplots(1,2)

for source in df['source'].unique():

    x = df.loc[df['source'] == source, 'value']
    y = df.loc[df['source'] == source, 'depth']

    sns.regplot(x,
                y,
                scatter = True,
                fit_reg = False,
                label = source,
                ax = ax1)
    ax1.legend()

    sns.distplot(x,
                 bins = 'auto',
                 norm_hist =True,
                 kde = True,
                 rug = True,
                 ax = ax2,
                 label = source)
    ax2.legend()
    ax2.relim()
    ax2.autoscale_view()
plt.show()

结果如下图所示。

enter image description here

如您所见,散点图和直方图之间的颜色不同。现在,我试过使用彩色托盘和其他所有东西,但没有奏效。谁能阐明我如何同步颜色?

谢谢。

最佳答案

使用绘图函数的color 参数。在此示例中,您的 for 循环中当前的 seaborn 调色板使用 itertools.cycle 逐一选择要绘制的颜色:

import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
import itertools
    
data = {'source':['B1','B1','B1','C2','C2','C2'],
        'depth':[1,4,9,1,3,10],
        'value':[10,4,23,78,24,45]}

df = pd.DataFrame(data)

f, (ax1, ax2) = plt.subplots(1,2)

# set palette 
palette = itertools.cycle(sns.color_palette())

# plotting 
for source in df['source'].unique():

    x = df.loc[df['source'] == source, 'value']
    y = df.loc[df['source'] == source, 'depth']

    # color
    c = next(palette)
    sns.regplot(x,
                y,
                scatter = True,
                fit_reg = False,
                label = source,
                ax = ax1,
                color=c)
    ax1.legend()

    sns.distplot(x,
                 bins = 'auto',
                 norm_hist =True,
                 kde = True,
                 rug = True,
                 ax = ax2,
                 label = source,
                 color=c)
    ax2.legend()
    ax2.relim()
    ax2.autoscale_view()

plt.show()

enter image description here

你可以自己设置color palette就像在this answer

关于python - 如何跨不同类型的 Seaborne/Matplotlib 子图同步颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823078/

相关文章:

python - Pandas 评估条件并转换为 0/1 int

带有 Pandas : How does one recover the non intersecting parts of two dataframes? 的 Python 2.7

python - 您可以仅将一些子图复制到新图形中吗?

python - 如何在 Python 中对 Matplotlib 进行线程化?

python - Django-Oscar 图像错误

python - 如何从 ctypes 数组中获取 ctypes 类型对象

python - 使用 django-oauth-toolkit 进行用户身份验证

python - 如何构造带 DateOffset 的 TimeGrouper?

python - Pandas 遍历数据框中的列以获取自定义 MySQL 插入字符串

python-3.x - basemap npstere 投影返回没有数据的空白 map