如何在seaborn散点图中添加x轴和y轴线

2024-05-23 16:30:56 发布

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

我使用以下代码创建散点图(以导入数据为例)。然而,创建的绘图没有x轴和y轴,这看起来很奇怪。我也想保持脸的颜色为白色

import seaborn as sns
tips = sns.load_dataset("tips")

fig, ax = plt.subplots(figsize=(10, 8))
sns.scatterplot(
    x='total_bill',
    y='tip',
    data=tips,
    hue='total_bill',
    edgecolor='black',
    palette='rocket_r',
    linewidth=0.5,
    ax=ax
)
ax.set(
    title='title',
    xlabel='total_bill',
    ylabel='tip',
    facecolor='white'
);

有什么建议吗?非常感谢

enter image description here


Tags: 数据代码import绘图title颜色asseaborn
1条回答
网友
1楼 · 发布于 2024-05-23 16:30:56

您似乎已经明确设置了默认的seaborn主题。没有边框(因此也没有x轴和y轴的线)、灰色面颜色和白色网格线。您可以使用sns.set_style("whitegrid")来拥有白色的面部颜色。还可以使用sns.despine()仅显示x轴和y轴,但在顶部和右侧不显示“脊椎”。有关微调绘图外观的详细信息,请参见Controlling figure aesthetics

这是一个比较。注意,应该在创建轴之前设置样式,因此出于演示目的plt.subplot一次创建一个轴

import matplotlib.pyplot as plt
import seaborn as sns

sns.set()  # set the default style
# sns.set_style('white')
tips = sns.load_dataset("tips")

fig = plt.figure(figsize=(18, 6))
for subplot_ind in (1, 2, 3):
    if subplot_ind >= 2:
        sns.set_style('white')
    ax = plt.subplot(1, 3, subplot_ind)
    sns.scatterplot(
        x='total_bill',
        y='tip',
        data=tips,
        hue='total_bill',
        edgecolor='black',
        palette='rocket_r',
        linewidth=0.5,
        ax=ax
    )
    ax.set(
        title={1: 'Default theme', 2: 'White style', 3: 'White style with despine'}[subplot_ind],
        xlabel='total_bill',
        ylabel='tip'
    )
    if subplot_ind == 3:
        sns.despine(ax=ax)
plt.tight_layout()
plt.show()

comparing seaborn themes

相关问题 更多 >