Scategory_scatter: 创建不同颜色类别的散点图
一个用于快速从 pandas DataFrame
或 NumPy ndarray
对象生成按类别着色的散点图的函数。
from mlxtend.general import category_scatter
概述
参考文献
- -
示例 1 - 从 Pandas DataFrame 创建类别散点图
import pandas as pd
from io import StringIO
csvfile = """label,x,y
class1,10.0,8.04
class1,10.5,7.30
class2,8.3,5.5
class2,8.1,5.9
class3,3.5,3.5
class3,3.8,5.1"""
df = pd.read_csv(StringIO(csvfile))
df
标签 | x | y | |
---|---|---|---|
0 | 类别 1 | 10.0 | 8.04 |
1 | 类别 1 | 10.5 | 7.30 |
2 | 类别 2 | 8.3 | 5.50 |
3 | 类别 2 | 8.1 | 5.90 |
4 | 类别 3 | 3.5 | 3.50 |
5 | 类别 3 | 3.8 | 5.10 |
绘制数据,其中类别由标签列 label_col
中的唯一值确定。x
和 y
值是我们想要绘制的 DataFrame 的列名。
import matplotlib.pyplot as plt
from mlxtend.plotting import category_scatter
fig = category_scatter(x='x', y='y', label_col='label',
data=df, legend_loc='upper left')
示例 2 - 从 NumPy 数组创建类别散点图
import numpy as np
from io import BytesIO
csvfile = """1,10.0,8.04
1,10.5,7.30
2,8.3,5.5
2,8.1,5.9
3,3.5,3.5
3,3.8,5.1"""
ary = np.genfromtxt(BytesIO(csvfile.encode()), delimiter=',')
ary
array([[ 1. , 10. , 8.04],
[ 1. , 10.5 , 7.3 ],
[ 2. , 8.3 , 5.5 ],
[ 2. , 8.1 , 5.9 ],
[ 3. , 3.5 , 3.5 ],
[ 3. , 3.8 , 5.1 ]])
现在,假设第一列代表标签,第二列和第三列分别代表 x
和 y
值。
import matplotlib.pyplot as plt
from mlxtend.plotting import category_scatter
fix = category_scatter(x=1, y=2, label_col=0,
data=ary, legend_loc='upper left')
API
category_scatter(x, y, label_col, data, markers='sxo^v', colors=('blue', 'green', 'red', 'purple', 'gray', 'cyan'), alpha=0.7, markersize=20.0, legend_loc='best')
用于绘制不同颜色/标记样式类别的散点图。
参数
-
x
: str 或 intx 轴值的 DataFrame 列名,或 NumPy ndarray 的列索引(整数)。
-
y
: stry 轴值的 DataFrame 列名,或 NumPy ndarray 的列索引(整数)
-
data
: Pandas DataFrame 对象或 NumPy ndarray。 -
markers
: str在标签类别中循环使用的标记。
-
colors
: tuple在标签类别中循环使用的颜色。
-
alpha
: float (默认值: 0.7)控制透明度的参数。
-
markersize
: float (默认值: 20.0)控制标记大小的参数。
-
legend_loc
: str (默认值: 'best')图例位置 {best, upper left, upper right, lower left, lower right} 如果 legend_loc=False 则不显示图例
返回值
fig
: matplotlig.pyplot figure 对象
示例
有关使用示例,请参阅 https://mlxtend.cn/mlxtend/user_guide/plotting/category_scatter/