Pandas/Pyplot中的散点图:如何按类别绘制

use*_*613 73 python matplotlib pandas

我正在尝试使用Pandas DataFrame对象在pyplot中创建一个简单的散点图,但是想要一种有效的方法来绘制两个变量,但是具有由第三列(键)指示的符号.我尝试过使用df.groupby的各种方法,但没有成功.下面是一个示例df脚本.这会根据'key1'为标记着色,但Id喜欢看到带有'key1'类别的图例.我接近了吗?谢谢.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
plt.show()
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 93

你可以使用scatter它,但这需要你的数字值,你key1不会有一个传说,正如你所注意到的那样.

最好只使用plot像这样的离散类别.例如:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend()

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您希望看起来像默认pandas样式,那么只需rcParams使用pandas样式表更新它并使用其颜色生成器.(我也在稍微调整一下这个传说):

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random')

fig, ax = plt.subplots()
ax.set_color_cycle(colors)
ax.margins(0.05)
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend(numpoints=1, loc='upper left')

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Bob*_*ley 45

这与Seaborn(pip install seaborn)作为oneliner 很简单

sns.pairplot(x_vars=["one"], y_vars=["two"], data=df, hue="key1", size=5) :

import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(1974)

df = pd.DataFrame(
    np.random.normal(10, 1, 30).reshape(10, 3),
    index=pd.date_range('2010-01-01', freq='M', periods=10),
    columns=('one', 'two', 'three'))
df['key1'] = (4, 4, 4, 6, 6, 6, 8, 8, 8, 8)

sns.pairplot(x_vars=["one"], y_vars=["two"], data=df, hue="key1", size=5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

以下是数据框供参考:

在此输入图像描述

由于数据中有三个可变列,您可能希望使用以下内容绘制所有成对维度:

sns.pairplot(vars=["one","two","three"], data=df, hue="key1", size=5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

https://rasbt.github.io/mlxtend/user_guide/plotting/category_scatter/是另一种选择.


CT *_*Zhu 19

有了plt.scatter,我只能想到一个:使用代理艺术家:

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)

ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)
Run Code Online (Sandbox Code Playgroud)

结果是:

在此输入图像描述


Arj*_*ijk 6

您可以使用df.plot.scatter,并将数组传递给c = argument,定义每个点的颜色:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
colors = np.where(df["key1"]==4,'r','-')
colors[df["key1"]==6] = 'g'
colors[df["key1"]==8] = 'b'
print(colors)
df.plot.scatter(x="one",y="two",c=colors)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Imp*_*est 6

从 matplotlib 3.1 开始,您可以使用.legend_elements(). 自动图例创建中显示了一个示例。优点是可以使用单个分散调用。

在这种情况下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), 
                  index = pd.date_range('2010-01-01', freq = 'M', periods = 10), 
                  columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)


fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ax.legend(*sc.legend_elements())
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果键不是直接作为数字给出的,它看起来像

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), 
                  index = pd.date_range('2010-01-01', freq = 'M', periods = 10), 
                  columns = ('one', 'two', 'three'))
df['key1'] = list("AAABBBCCCC")

labels, index = np.unique(df["key1"], return_inverse=True)

fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = index, alpha = 0.8)
ax.legend(sc.legend_elements()[0], labels)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Nip*_*tra 5

您还可以尝试Altairggpot,它们专注于声明性可视化。

import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))
Run Code Online (Sandbox Code Playgroud)

Altair 代码

from altair import Chart
c = Chart(df)
c.mark_circle().encode(x='x', y='y', color='label')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot 代码

from ggplot import *
ggplot(aes(x='x', y='y', color='label'), data=df) +\
geom_point(size=50) +\
theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述