python 在海上创作并排的小提琴情节

ewm0tg9j  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(122)

我试图使用Matplotlib和Seaborn创建并排的小提琴情节,但我很难让它们正确显示(我一直发现它们会被叠加)。我想比较数据集中不同元素类型的平均Phast分数。目前,我的代码将小提琴图显示为单独的子图。

# Create a new figure and subplots with 1 row and 2 columns
fig, axes = plt.subplots(1, 2, figsize=(12, 6))

# First violin plot
sns.violinplot(
    y=df['avg_phast_score'],
    x=df['main_category'],
    ax=axes[0]  # Assign the first subplot to the first column
)
# Set title and labels for the first subplot
axes[0].set_title('element regions')
axes[0].set_xlabel('Element Type')
axes[0].set_ylabel('Average Phast Score')
axes[0].set_ylim([-.1, .2])  # Set the y-axis limits for the first subplot
axes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=90)  # Rotate x-axis labels

# Second violin plot
sns.violinplot(
    y=df['control_score'],
    x=df['main_category'],
    ax=axes[1]  # Assign the second subplot to the second column
)

# Set title and labels for the second subplot
axes[1].set_title('control')
axes[1].set_xlabel('Element Type')
axes[1].set_ylabel('Average Phast Score')
axes[1].set_ylim([-.1, .2])  # Set the y-axis limits for the second subplot
axes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=90)  # Rotate x-axis labels

# Adjust the spacing between the subplots
plt.tight_layout()
# Display the plot
plt.show()
2hh7jdfx

2hh7jdfx1#

在代码段中使用了两个单独的DataFrame对象:final_dfdf。确保每个子图都使用了适当的DataFrame。
当使用set_xticklabels设置x轴标签时,必须以字符串列表的形式给予标签。可以使用旋转参数,方法与旋转标签的方法相同。

fig, axes = plt.subplots(1, 2, figsize=(12, 6))

sns.violinplot(
    y=final_df['avg_phast_score'],
    x=final_df['main_category'],
    ax=axes[0]
)

axes[0].set_title('Element Regions')
axes[0].set_xlabel('Element Type')
axes[0].set_ylabel('Average Phast Score')
axes[0].set_ylim([-0.1, 0.2])  # Set the y-axis limits for the first subplot
axes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=90)  

sns.violinplot(
    y=df['control_score'],
    x=df['main_category'],
    ax=axes[1] 
)

axes[1].set_title('Control')
axes[1].set_xlabel('Element Type')
axes[1].set_ylabel('Average Phast Score')
axes[1].set_ylim([-0.1, 0.2])  
axes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=90)  

plt.tight_layout()
plt.show()

相关问题