我正在尝试创建一个包含两个地 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()
结果如下图所示。
如您所见,散点图和直方图之间的颜色不同。现在,我试过使用彩色托盘和其他所有东西,但没有奏效。谁能阐明我如何同步颜色?
谢谢。
最佳答案
使用绘图函数的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()
你可以自己设置color palette就像在this answer
关于python - 如何跨不同类型的 Seaborne/Matplotlib 子图同步颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823078/