如何在 Seaborn 中将图形样式转换为 Whitegrid?


Seaborn 是 Python 中一个流行的数据可视化库,它提供各种样式来增强绘图的视觉效果。其中一个可用的样式是“whitegrid”,它提供了一个带有网格线的白色背景。在 Seaborn 中更改图形样式是一个简单的过程,它可以极大地影响我们可视化的美观性。

在这篇文章中,我们将了解如何在 seaborn 中将图形样式更改为白色网格。要在 Seaborn 中将图形样式更改为“whitegrid”,我们可以按照以下步骤操作。

安装 Seaborn

首先,我们应该检查我们的 Python 环境中是否已安装 Seaborn。我们可以使用 Python 工作环境中的pip命令安装它。

pip install seaborn

导入必要的库

在我们的 Python 脚本或 Jupyter Notebook 中,接下来我们必须导入所需的库,例如 Seaborn 和 Matplotlib.pyplot。

import seaborn as sns import matplotlib.pyplot as plt

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

设置图形样式

接下来,我们必须使用'sns.set_style()'函数将图形样式设置为“whitegrid”。此函数修改了 Matplotlib 的默认样式。

sns.set_style("whitegrid")

这行代码将图形样式设置为“whitegrid”。

绘制数据

现在,我们可以使用 Seaborn 和 Matplotlib 创建和自定义我们的绘图。这是一个绘制条形图的简单示例。

示例

在此示例中,'sns.barplot()' 使用 Seaborn 创建条形图。以下几行使用 Matplotlib 设置 x 轴标签、y 轴标签和标题。最后,'plt.show()' 显示绘图。

import seaborn as sns import matplotlib.pyplot as plt sns.set_style("whitegrid") x = ["A", "B", "C", "D"] y = [10, 20, 15, 25] # Create a bar plot sns.barplot(x=x, y=y) # Set labels and title plt.xlabel("Categories") plt.ylabel("Values") plt.title("Bar Chart") # Display the plot plt.show()

输出

自定义

我们可以使用各种 Seaborn 函数和 Matplotlib 选项进一步自定义我们的绘图。例如,我们可以调整调色板、字体大小、网格线等。有关更多自定义选项,请参阅 Seaborn 文档。

以下几行代码演示了一些额外的自定义,其中'sns.set_palette()' 将调色板更改为“husl”。'plt.xticks()' 和 'plt.yticks()' 分别设置 x 轴和 y 轴刻度的字体大小。'plt.grid()' 以虚线样式和 0.5 的线宽向绘图添加网格线。

示例

import seaborn as sns import matplotlib.pyplot as plt sns.set_style("whitegrid") x = ["A", "B", "C", "D"] y = [10, 20, 15, 25] # Create a bar plot sns.barplot(x=x, y=y) # Set labels and title plt.xlabel("Categories") plt.ylabel("Values") plt.title("Bar Chart") # Customizing the Chart sns.set_palette("husl") # Change the color palette plt.xticks(fontsize=10) # Set x-axis tick font size plt.yticks(fontsize=10) # Set y-axis tick font size plt.grid(True, linestyle="--", linewidth=0.1) # Display the plot plt.show()

输出

更新于: 2023 年 8 月 2 日

171 次查看

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告