如何在不同类型的子图上同步颜色Seaborne/Matplotlib [英] How to sync Colors across Subplots of different types Seaborne / Matplotlib
问题描述
我正在尝试创建一个包含两个图的子图.第一个图本质上是散点图(我正在使用regplot),第二个图是直方图.
I am trying to create a subplot with two plots. The first plot is essentially a scatter plot (i'm using regplot) and the second is a histogram.
我的代码如下:
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()
结果如下所示.
如您所见,散点图和直方图之间的颜色是不同的.现在,我在玩各种颜色的托盘,但都没有用.谁能阐明我如何同步颜色?
As you can see, the colors between the scatter and the histogram are different. Now, I had a play around with color pallets and all, which has not worked. Can anyone shed any light on how I can sync the colors?
谢谢.
推荐答案
使用绘图功能的color
参数.在此示例中,从您的for循环中当前的深蓝色调色板中逐个选择itertools.cycle
种要绘制的颜色:
Use color
argument of plotting functions. In this example from current seaborn color palette in your for cycle with itertools.cycle
colors to plot are selected one by one:
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()
您可以设置自己的调色板,如
You can set your own color palette like in this answer
这篇关于如何在不同类型的子图上同步颜色Seaborne/Matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!