matplotlib 添加垂直线以分隔条件分割箱线图

uidvcgyl  于 2023-05-29  发布在  其他
关注(0)|答案(2)|浏览(155)

我试图在我的海运箱线图上实现垂直线来分隔每列,到目前为止,我似乎只能添加穿过中间的主要线条ax.xaxis.grid(True, which='major')。下面是我的代码和我试图实现的图像。谢谢!

# Custom palette
my_pal = {"Year A": "#e42628", "Year B": "#377db6"}

plt.figure(figsize=(16, 10))
sns.axes_style("whitegrid")
ax = sns.boxplot(x='variable', y="value", hue="Condition", showmeans=True, data=df, palette=my_pal, meanprops={"marker":"s","markerfacecolor":"white", "markeredgecolor":"black"})
plt.ylabel("Temperature (\xb0C)")
#ax.axvline(linewidth=2, color='r')
ax.xaxis.grid(True, which='major')

lqfhib0f

lqfhib0f1#

箱形图的默认宽度为0.5(或0.15 x [极端位置之间的距离],如果更小)。
如果你的宽度是0.5,你可以这样做:

import seaborn as sns, matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
ax = sns.boxplot(x='day',y='total_bill',hue='sex',data=tips)
[ax.axvline(x+.5,color='k') for x in ax.get_xticks()]
plt.show()

示例:

yyhrrdl8

yyhrrdl82#

可以按如下所示定位次要Xtick,并将其用于栅格:

from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns
import pandas as pd
import numpy as np

N = 200
df = pd.DataFrame({'variable': np.repeat(list('ABCDEFGHIJ'), N // 10),
                   'value': np.random.uniform(10, 25, N),
                   'Condition': np.random.choice(['Year A', 'Year B'], N)})

# Custom palette
my_pal = {"Year A": "#e42628", "Year B": "#377db6"}

plt.figure(figsize=(16, 10))
sns.axes_style("whitegrid")
ax = sns.boxplot(x='variable', y="value", hue="Condition", showmeans=True, data=df, palette=my_pal,
                 meanprops={"marker": "s", "markerfacecolor": "white", "markeredgecolor": "black"})
plt.ylabel("Temperature (°C)")
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
ax.xaxis.grid(True, which='minor', color='black', lw=2)

plt.show()

相关问题