简体   繁体   English

熊猫中的散点图:按类别绘制具有不同颜色和形状的图形

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

I would like to plot a data-set by its categories, using geometric shapes such as circle, triangle and square to represent category 1 and colors to represent category 2. The output would have varying combination of the geometric shapes and colors and the legend would list the attributes of the categories separately ie: 我想按类别绘制数据集,使用诸如圆形,三角形和正方形的几何形状表示类别1,使用颜色表示类别2。输出将具有几何形状和颜色的不同组合,图例将分别列出类别的属性,即:

circle = a 圆= a
triangle = b 三角形= b
square = c 平方= c

red = I 红色=我
green = II 绿色= II
blue = III 蓝色= III

Looking for solutions I found following posts which would only give solutions for one specific geometric shape having one specific color. 在寻找解决方案时,我发现以下文章仅针对具有一种特定颜色的一种特定几何形状提供解决方案。

I tried to work something out with the code from one of the posts but without success. 我尝试使用其中一篇文章中的代码来解决问题,但是没有成功。

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()

you can try this code block 你可以试试这个代码块

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()

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM