我正在尝试更改Seaborn中小提琴的边缘颜色。下面的代码为我工作。
ax=sns.violinplot(data=df, x="#", y="SleepAmount", hue="Thr", palette=my_pal, split=True,linewidth = 1, inner=None)
ax2 = sns.pointplot(x="#", y="SleepAmount", hue="Thr", data=df, dodge=0.3, join=False, palette=['black'], ax=ax,errwidth=1, ci="sd", markers="_") plt.setp(ax.collections, edgecolor="k")
plt.setp(ax2.collections, edgecolor="k")
Run Code Online (Sandbox Code Playgroud)
但是当我使用facetgrid时,我不知道如何采用plt.setp(ax.collections, edgecolor="k")下面的facetgrid地图。
g = sns.FacetGrid(df, col="temperature",sharey=True)
g=g.map(sns.violinplot,"#", "latency", "Thr", palette=my_pal, split=True, linewidth = 1, inner=None,data=df)
g=g.map(sns.pointplot, "#", "latency", "Thr", data=df, dodge=0.3, join=False, palette=['black'],errwidth=1, ci="sd", markers="_")
Run Code Online (Sandbox Code Playgroud)
我已经尝试了很多东西。喜欢,
sns.set_edgecolor('k')
sns.set_style( {"lines.color": "k"})
sns.set_collections({'edgecolor':'k'})
g.fig.get_edgecolor()[0].set_edge("k")
g.setp.get_collections()[0].set_edgecolor("k")
Run Code Online (Sandbox Code Playgroud)
谁能帮我吗?
另一个快速的问题是,除了whitegrid或darkgrid之外,是否可以更改网格颜色?Facecolor对我不起作用,因为它会为所有背景(包括刻度和标签区域)上色。我只想更改网格区域。谢谢!
linewidth : float, 可选 构成绘图元素的灰线的宽度。
所以它看起来很硬编码。
事实上,引用seaborn的画小提琴代码:
def draw_violins(self, ax):
"""Draw the violins onto `ax`."""
fill_func = ax.fill_betweenx if self.orient == "v" else ax.fill_between
for i, group_data in enumerate(self.plot_data):
kws = dict(edgecolor=self.gray, linewidth=self.linewidth)
Run Code Online (Sandbox Code Playgroud)
所以我想你不能用 seaborn 的 API 轻松做到这一点。或者如果你喜欢黑客/猴子修补seaborn的课程......
import seaborn.categorical
seaborn.categorical._Old_Violin = seaborn.categorical._ViolinPlotter
class _My_ViolinPlotter(seaborn.categorical._Old_Violin):
def __init__(self, *args, **kwargs):
super(_My_ViolinPlotter, self).__init__(*args, **kwargs)
self.gray='red'
seaborn.categorical._ViolinPlotter = _My_ViolinPlotter
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time", row="smoker")
g.map(sns.violinplot, "tip")
plt.show()
Run Code Online (Sandbox Code Playgroud)
然而,seaborn 的 FacetGrid 是基于 matplotlib 的子图。一旦准备好绘制,也许有一个改变图表的技巧。
实际上,您已经很接近了(或者当时这可能不起作用)。无论如何,您可以从中获取axis对象FacetGrid,然后为第一个条目设置边缘颜色,collections如下所示:
import seaborn as sns
tips = sns.load_dataset('tips')
grid = sns.FacetGrid(tips, col="time", row="smoker")
grid.map(sns.violinplot, "tip", color='white')
for ax in grid.axes.flatten():
ax.collections[0].set_edgecolor('red')
Run Code Online (Sandbox Code Playgroud)