Pandas 中的散点图:按类别绘制,具有不同的颜色和形状组合

Scatter plots in Pandas: Plot by category with different color and shape combinations

我想按类别绘制数据集,使用圆形、三角形和正方形等几何形状来表示类别 1,使用颜色来表示类别 2。输出将具有不同的几何形状组合和颜色和图例将分别列出类别的属性,即:

圆=一个
三角形 = b
正方形 = c

红色=我
绿色 = II
蓝色 = III

在寻找解决方案时,我发现了以下帖子,这些帖子只会为具有一种特定颜色的特定几何形状提供解决方案。

我尝试使用其中一个帖子中的代码解决问题,但没有成功。

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

np.random.seed(1983)
num = 10
x, y = np.random.random((2, num))
cat1 = np.random.choice(['a', 'b', 'c'], num)
cat2 = np.random.choice(['I', 'II', 'III'], num)
df = pd.DataFrame(dict(x=x, y=y, cat1=cat1, cat2=cat2))

groups = df.groupby(['cat1', 'cat2'])

fig, ax = plt.subplots()
for name, group in groups:
ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend()

plt.show()

你可以试试这个代码块

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

#Create mapping dictionary that you want
marker_dict = {'a':'o','b':'^','c':'s'}
color_dict = {'I':'red', 'II':'green', 'III':'blue'}

np.random.seed(1983)
num = 10
x, y = np.random.random((2, num))
cat1 = np.random.choice(['a', 'b', 'c'], num)
cat2 = np.random.choice(['I', 'II', 'III'], num)
df = pd.DataFrame(dict(x=x, y=y, cat1=cat1, cat2=cat2))

groups = df.groupby(['cat1', 'cat2'])

fig, ax = plt.subplots()
ax.margins(0.05)
for name, group in groups:
    marker = marker_dict[name[0]]
    color = color_dict[name[1]]
    ax.plot(group.x, group.y, marker=marker, linestyle='', ms=12, label=name,color=color)
ax.legend()

plt.show()

希望对您有所帮助。