如何在matplotlib / seaborn子图中使用相同的调色板?

时间:2019-09-18 14:26:46

标签: matplotlib seaborn

我正在使用matplotlib和seaborn制作一组子图,并且我希望顶部和底部子图之间的调色板相同。

奇怪的是,对于某些类型的绘图(例如顶部的lineplot和底部的distplot),调色板会自动相同。对于其他人(例如顶部的regplot和底部的distplot)则不是。

这是我的意思的示例:

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

sns.set(style='darkgrid')

x = np.arange(1,1001)
x=np.random.lognormal(0,1,1001)

fig1, ax1 = plt.subplots(2,1)

sns.lineplot(x, x*2, label ='2x', ax=ax1[0])
sns.lineplot(x, x*3, label ='3x', ax=ax1[0])

sns.distplot( 2*x, bins = 100, ax = ax1[1], label='2x'  )
sns.distplot( 3*x, bins = 100, ax = ax1[1], label='3x'  )

for a in ax1:
    a.legend()


fig2, ax2 = plt.subplots(2,1)
sns.regplot(x, x*2, label ='2x', ax=ax2[0])
sns.regplot(x, x*3, label ='3x', ax=ax2[0])

sns.distplot( 2*x, bins = 100, ax = ax2[1], label='2x'  )
sns.distplot( 3*x, bins = 100, ax = ax2[1], label='3x'  )

for a in ax2:
    a.legend()

根据此answer,以下代码可以正常工作。

但是,我想知道:

  1. 为什么调色板与某些图相同,但与其他图不同?技术原因是什么?
  2. 是否有一种更优雅的方式来重置调色板,而不必每次都指定color = next(palette)

代码:

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

fig3, ax3 = plt.subplots(2,1)
sns.regplot(x, x*2, label ='2x', ax=ax3[0], color = next(palette) )
sns.regplot(x, x*3, label ='3x', ax=ax3[0], color = next(palette))

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

sns.distplot( 2*x, bins = 100, ax = ax3[1], label='2x', color = next(palette)  )
sns.distplot( 3*x, bins = 100, ax = ax3[1], label='3x' , color = next(palette) )

for a in ax3:
    a.legend()

0 个答案:

没有答案