作者|Zolzaya Luvsandorj
编译|VK
来源|Towards Datas Science

在这篇文章中,我们将探讨一些简单的方法来定制你的图表,使它们在美学上更好。我希望这些简单的技巧能帮助你得到更好看的图。

基线图

本文中的脚本在Jupyter笔记本中的python3.8.3中进行了测试。

让我们使用Seaborn内置的penguins数据集作为样本数据:

# 导入包
import matplotlib.pyplot as plt
import seaborn as sns

# 导入数据
df = sns.load_dataset('penguins').rename(columns={'sex': 'gender'})
df

我们将使用默认图表设置构建标准散点图,以将其用作基线:

# 图
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender')

我们将看到这个图如何随着每一个技巧而改变。


技巧

你将看到,前两个技巧用于单个绘图,而其余四个技巧用于更改所有图表的默认设置。

技巧1:分号

你有没有注意到在上一个图中,文本输出就在图表的正上方?抑制此文本输出的一个简单方法是在绘图末尾使用;

# 图
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender');

只需在代码末尾添加;就可以得到更清晰的输出。

技巧2:plt.figure()

绘图通常可以从调整大小中获益。如果我们想调整大小,我们可以这样做:

# 图
plt.figure(figsize=(9, 5))
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender');

当我们调整大小时,图例移到了左上角。让我们将图例移到图表之外,这样它就不会意外地覆盖数据点:

# 图
plt.figure(figsize=(9, 5))
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender')
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1));

如果你想知道如何知道figsize()bbox_to_anchor()使用什么数的字组合,则需要尝试哪些数字最适合绘图。

技巧3:sns.set_style()

如果不喜欢默认样式,此函数有助于更改绘图的整体样式。这包括轴的颜色和背景。让我们将样式更改为whitegrid,并查看打印外观如何更改:

# 更改默认样式
sns.set_style('whitegrid')

# 图
plt.figure(figsize=(9, 5))
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender')
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1));

这里还有一些其他的选择可以尝试:“darkgrid”、“dark”和“ticks”来找到你更喜欢的那个。

技巧4:sns.set_context()

在前面的图中,标签尺寸看起来很小。如果不喜欢默认设置,我们使用sns.set_context()可以更改上下文参数。

我使用这个函数主要是为了控制绘图中标签的默认字体大小。通过更改默认值,我们可以节省时间,而不必为单个绘图的不同元素(例如轴标签、标题、图例)调整字体大小。让我们把上下文改成“talk”,再看看图:

# 默认上下文更改
sns.set_context('talk')

# 图
plt.figure(figsize=(9, 5))
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender')
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1));

它更容易辨认,不是吗?另一个可以尝试的选项是:“poster”,这将增加默认大小甚至更多。

技巧5:sns.set_palette()

如果你想将默认调色板自定义为你喜欢的颜色组合,此功能非常方便。我们可以使用Matplotlib中的彩色映射。这里是从颜色库中选择的。让我们将调色板更改为“rainbow”并再次查看该图:

# 更改默认调色板
sns.set_palette('rainbow')

# 图
plt.figure(figsize=(9, 5))
sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', 
                alpha=0.7, hue='species', size='gender')
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1));

如果找不到你喜欢的Matplotlib颜色映射,可以手动选择颜色来创建自己独特的调色板。

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/panchuangai/p/13817992.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!