第二个y轴和垂直线

2024-09-29 21:51:37 发布

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

我使用以下代码创建violinplot:

import seaborn as sns

ax = sns.violinplot(data=df[['SoundProduction','SoundForecast','diff']])
ax.set_ylabel("Sound power level [dB(A)]")

结果如下:

violinplot

有没有什么方法可以把diff绘制在第二个y轴上,这样所有三个序列都变得清晰可见?你知道吗

另外,有没有办法在两个系列之间画一条垂直线?在这种情况下,我希望在SoundForecastdiff之间有一条垂直线,一旦它们被绘制在两个不同的轴上。你知道吗


Tags: 代码importdfdataas绘制diffseaborn
1条回答
网友
1楼 · 发布于 2024-09-29 21:51:37

您可以使用多个子图来实现这一点,这些子图可以使用plt.subplots轻松设置(请参阅更多subplot examples)。你知道吗

这允许您在适当的比例上显示分布,并且不会“浪费”显示空间。大多数(全部?)seaborn的plotting函数接受ax=参数,因此您可以设置渲染绘图的轴。轴之间也有明显的分隔。你知道吗

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# generate some random distribution data
n = 800 # samples
prod = 95 + 5 * np.random.beta(0.6, 0.5, size=n); # a bimodal distribution
forecast = prod + 3*np.random.randn(n) # forecast is noisy estimate around the "true" production
diff = prod-forecast  # should be with mu 0 sigma 3
df = pd.DataFrame(np.array([prod, forecast, diff]).T, columns=['SoundProduction','SoundForecast','diff']); 

# set up two subplots, with one wider than the other
fig, ax = plt.subplots(1,2, num=1,  gridspec_kw={'width_ratios':[2,1]})

# plot violin distribution estimates separately so the y-scaling makes sense in each group
sns.violinplot(data=df[['SoundProduction','SoundForecast']], ax=ax[0])
sns.violinplot(data=df[['diff']], ax=ax[1])

enter image description here

相关问题 更多 >

    热门问题