对数标度的Seaborn条带图

2024-10-08 20:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pyplot.boxplots以对数比例绘制箱线图,然后我想使用seaborn在其顶部绘制Swarmlot/strip plot。 然而,《海底生物》把整个规模搞得一团糟,情节也非常荒谬。知道我如何在seaborn提供定制职位吗

att1= np.sort(np.unique(df1.att1))

w = 0.085
width = lambda p, w: 10 ** (np.log10(p) + w / 2.) - 10 ** (np.log10(p) - w / 2.)
custom_widths = width(freqns, w)


ax.boxplot([df1[df1.att1== xi].att2 for xi in att1], positions=att1,
           boxprops={'facecolor': 'none'}, medianprops={'color': 'black'}, patch_artist=True,
           widths=custom_widths)
ax.set_xscale("log")
fig.set_size_inches(10.5, 8)
means = [np.median(df1[df1.Frequency == xi].CapDensity) for xi in freqs]
plt.plot(freqns, means, '--k*', lw=1.2)

这是不带条形图的图像: This is image w/o strip plot

sns.stripplot(x="Frequency", y="CapDensity",data=df1, edgecolor="black", linewidth=.3, jitter=0.1, zorder=0.5, ax=ax)

这是我在箱线图的顶部做条形图的时候

This is when I do strip plot on top of boxplot


Tags: forplotcustomnp绘制seabornaxwidth
1条回答
网友
1楼 · 发布于 2024-10-08 20:26:27

问题是您使用att1作为箱线图的位置,而seaborn将始终在内部位置0,1,2,3,...放置条线图。最简单的解决方案是通过matplotlib创建条带图。(创建Swarmlot要复杂得多。)

假设您有与上一个问题类似的数据,可以创建这样一个图:

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({'x': np.random.choice([1, 3, 5, 8, 10, 30, 50, 100], 500),
                   'y': np.random.normal(750, 20, 500)})

xvals = np.unique(df.x)
w = 0.085
width = lambda p, w: 10 ** (np.log10(p) + w / 2.) - 10 ** (np.log10(p) - w / 2.)
custom_widths = width(xvals, w)

fig, ax = plt.subplots(figsize=(12, 4))
ax.set_xscale('log')
ax.boxplot([df[df.x == xi].y for xi in xvals],
           positions=xvals, showfliers=False,
           boxprops={'facecolor': 'none'}, medianprops={'color': 'black'}, patch_artist=True,
           widths=custom_widths)
medians = [np.median(df[df.x == xi].y) for xi in xvals]
ax.plot(xvals, medians, ' k*', lw=2)
ax.set_xticks(xvals)
for xi, wi in zip(xvals, custom_widths):
    yis = df[df.x == xi].y
    ax.scatter(xi + np.random.uniform(-wi / 2, wi / 2, yis.size), yis)
plt.show()

example plot

相关问题 更多 >

    热门问题