如何在Python中使用Matplotlib将图例添加到由变量着色的散点图

如何在Python中使用Matplotlib将图例添加到由变量着色的散点图

Matplotlib是一个功能强大的Python图形库,它有多种方法为散点图添加颜色并指定图例。在本文中,我们将学习如何向散点图添加正确的图例,该散点图由作为数据一部分的变量着色。

让我们加载Pandas和Matplotlib的pyplot

import pandas as pd
import matplotlib.pyplot as plt

我们将使用Palmer penguins的数据绘制散点图。我们在datavizpyr.com的github页面上有此数据

penguins_data="https://raw.githubusercontent.com/datavizpyr/data/master/palmer_penguin_species.tsv"
# load penguns data with Pandas read_csv
df = pd.read_csv(penguins_data, sep="\t")

在这里,我们使用Pandas的dropna()函数删除所有丢失的数据

df = df.dropna()
df.head()
    species island  culmen_length_mm    culmen_depth_mm flipper_length_mm   body_mass_g sex
0   Adelie  Torgersen   39.1    18.7    181.0   3750.0  MALE
1   Adelie  Torgersen   39.5    17.4    186.0   3800.0  FEMALE
2   Adelie  Torgersen   40.3    18.0    195.0   3250.0  FEMALE
4   Adelie  Torgersen   36.7    19.3    193.0   3450.0  FEMALE
5   Adelie  Torgersen   39.3    20.6    190.0   3650.0  MALE

首先,让我们开始使用Matplotlib的散点函数制作散点图。我们使用scatter()函数中的" c "参数来根据数据框架中的物种变量为数据点着色。

plt.figure(figsize=(8,6))
plt.scatter(df.culmen_length_mm, 
            df.culmen_depth_mm,
            s=150,
            c=df.species.astype('category').cat.codes)
plt.xlabel("Culmen Length", size=24)
plt.ylabel("Culmen Depth", size=24)
plt.savefig("scatterplot_point_colored_by_variable_matplotlib_Python.png",
                    format='png',dpi=150)

在这里插入图片描述

请注意,由变量着色的散点图缺少描述我们所看到的集群含义的图例。

向Matplotlib散点图添加图例

我们可以尝试通过使用Matplotlib中的legend()函数将图例添加到由变量着色的散点图中。在legend()中,我们通过从情节中提取图例元素来指定标题和句柄。

plt.figure(figsize=(8,6))
scatter = plt.scatter(df.culmen_length_mm, 
            df.culmen_depth_mm,
            s=150,
            c=df.species.astype('category').cat.codes)
plt.xlabel("Culmen Length", size=24)
plt.ylabel("Culmen Depth", size=24)
# add legend to the plot with names
plt.legend(handles=scatter.legend_elements()[0], 
           title="species")
plt.savefig("scatterplot_colored_by_variable_legend_first_try_matplotlib_Python.png",
                    format='png',dpi=150)

首先尝试将图例添加到scatterplot matplotlib
在这里插入图片描述

我们第一次尝试添加图例的效果并不好。我们可以看到,我们有一个带有颜色的图例,但没有变量名。
我们没有得到图例标签,主要是因为,我们用数值代码为物种变量着色散点图。注意,我们使用" df.species.astype(’ category ').cat。代码”来给数据点上色。
我们通常可以使用Matplotlib的legend()函数的参数“labels”来为图例指定标签。我们首先用一个物种名称列表来定义标签。

plt.figure(figsize=(8,6))
sp_names = ['Adelie', 'Gentoo', 'Chinstrap']
scatter = plt.scatter(df.culmen_length_mm, 
            df.culmen_depth_mm,
            s=150,
            c=df.species.astype('category').cat.codes)
plt.xlabel("Culmen Length", size=24)
plt.ylabel("Culmen Depth", size=24)
# add legend to the plot with names
plt.legend(handles=scatter.legend_elements()[0], 
           labels=sp_names,
           title="species")
plt.savefig("scatterplot_colored_by_variable_with_legend_matplotlib_Python.png",
                    format='png',dpi=150)

现在,我们有了用变量着色的散点图的图例。
在这里插入图片描述
原文: How to Add Legend to Scatterplot Colored by a Variable with Matplotlib in Python
datavizpyr · May 8, 2021 ·

matplotlib.legend() 函数

参数详解:见 Matplotlib legend参数详解

简单使用
1.设置图例的位置

plt.legend(loc=' ')

2.设置图例字体大小

fontsize : int or float or {
    
    ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

3.设置图例边框及背景

plt.legend(loc='best',frameon=False) #去掉图例边框
plt.legend(loc='best',edgecolor='blue') #设置图例边框颜色
plt.legend(loc='best',facecolor='blue') #设置图例背景颜色,若无边框,参数无效

4.设置图例标题

legend = plt.legend(["BJ", "SH"], title='Beijing VS Shanghai')
#或者 
plt.plot(["BJ", "SH"],loc='upper left',title='Beijing VS Shanghai')

5.设置图例名字及对应关系

legend = plt.legend([p1, p2], ["BJ", "SH"])

示例

import matplotlib.pyplot as plt
import numpy as np   
x = np.arange(0,10,1)
plt.plot(x,x,'r--',x,np.cos(x),'g--',marker='*')
plt.xlabel('row')
plt.ylabel('cow')
plt.legend(["BJ","SH"],loc='upper left',loc='upper left')
plt.show()

官方文档: https://matplotlib.org/api/legend_api.html?highlight=legend#module-matplotlib.legend

猜你喜欢

转载自blog.csdn.net/yxn4065/article/details/128909915