在 Python 中创建多色散点图
Creating multi colored scatterplot in Python
我有一个 pandas 数据框,其中包含我想要绘制的数据,但我想根据动物的性别更改点的颜色。我已经尝试了很多不同的方法来让它工作。首先,我尝试根据名为 'Sex'
的 df 列索引字典
figure = plt.figure(figsize=(20, 6))
axes = figure.add_subplot(1, 2, 1)
clr = {'M':'firebrick','F':'blueviolet', 'I':'beige'}
axes.scatter( data[ "Whole Weight"], data['Shucked Weight'],color=clr[str(data['Sex'])])
axes.set_ylabel( "Shucked Weight")
axes.set_xlabel( "Whole Weight")
axes.set_title("Whole Weight vs. Shucked Weight")
plt.show()
plt.close()
这给了我一堆关键错误。接下来我尝试遍历 df 并根据行值手动添加列:
for x1 in data['Sex']:
if x1 == 'M':
print(x1,)
data['color'] = 'firebrick'
elif x1 == 'F':
data['color'] = 'blueviolet'
else:
data['color'] = 'bisque1'
我试着从头开始制作一本字典,其中包含以下值:
weight_dict = pd.DataFrame(dict(whole = data['Whole Weight'], shucked = data['Shucked Weight'], sex = data['Sex'], color= some if statement that choked))
我尝试使用np.where声明,但我有3个性别选项(男性,女性和婴儿,缩写为M,F,I)
data['color'] = np.where(data.Sex == 'M', 'Firebrick', (data.Sex == 'F', 'blueviolet','beige'))
终于我成功了:
def label_color(row):
if row['Sex'] == 'M':
return 'firebrick'
elif row['Sex'] == 'F':
return 'blueviolet'
else:
return 'beige'
data['color'] = data.apply(lambda row: label_color(row), axis=1)
但我对解决方案不是很满意。我真的希望第一个解决方案在我只有一个自定义字典并在调用 axes.scatter 期间查找它的地方工作,但错误只是奇怪且无法理解。
有没有更简单的方法来解决这个问题?
我认为您在第一次尝试时几乎就成功了。
我会将字典应用于将性别映射到颜色的新列。像
df = pd.DataFrame(columns=["ww", "sw", "sex"])
df["ww"] = np.random.randn(500)
df["sw"] = np.random.randn(500)
df["sex"] = np.random.choice(["M", "F", "I"], size=500)
clr = {'M':'firebrick','F':'blueviolet', 'I':'yellow'}
df["color"] = df["sex"].apply(lambda x: clr[x])
plt.scatter(df["ww"], df["sw"], color=df["color"], alpha=0.7)
或者,如果您不想要新列,或者字典在分散调用之间发生变化,您可以这样做
plt.scatter(df["ww"], df["sw"], color=df["sex"].apply(lambda x: clr[x]), alpha=0.7)
不确定是否有仅使用字典的更好解决方案,但鉴于您已经在 pandas 中拥有数据,我认为可以使用它。
我有一个 pandas 数据框,其中包含我想要绘制的数据,但我想根据动物的性别更改点的颜色。我已经尝试了很多不同的方法来让它工作。首先,我尝试根据名为 'Sex'
的 df 列索引字典figure = plt.figure(figsize=(20, 6))
axes = figure.add_subplot(1, 2, 1)
clr = {'M':'firebrick','F':'blueviolet', 'I':'beige'}
axes.scatter( data[ "Whole Weight"], data['Shucked Weight'],color=clr[str(data['Sex'])])
axes.set_ylabel( "Shucked Weight")
axes.set_xlabel( "Whole Weight")
axes.set_title("Whole Weight vs. Shucked Weight")
plt.show()
plt.close()
这给了我一堆关键错误。接下来我尝试遍历 df 并根据行值手动添加列:
for x1 in data['Sex']:
if x1 == 'M':
print(x1,)
data['color'] = 'firebrick'
elif x1 == 'F':
data['color'] = 'blueviolet'
else:
data['color'] = 'bisque1'
我试着从头开始制作一本字典,其中包含以下值:
weight_dict = pd.DataFrame(dict(whole = data['Whole Weight'], shucked = data['Shucked Weight'], sex = data['Sex'], color= some if statement that choked))
我尝试使用np.where声明,但我有3个性别选项(男性,女性和婴儿,缩写为M,F,I)
data['color'] = np.where(data.Sex == 'M', 'Firebrick', (data.Sex == 'F', 'blueviolet','beige'))
终于我成功了:
def label_color(row):
if row['Sex'] == 'M':
return 'firebrick'
elif row['Sex'] == 'F':
return 'blueviolet'
else:
return 'beige'
data['color'] = data.apply(lambda row: label_color(row), axis=1)
但我对解决方案不是很满意。我真的希望第一个解决方案在我只有一个自定义字典并在调用 axes.scatter 期间查找它的地方工作,但错误只是奇怪且无法理解。
有没有更简单的方法来解决这个问题?
我认为您在第一次尝试时几乎就成功了。
我会将字典应用于将性别映射到颜色的新列。像
df = pd.DataFrame(columns=["ww", "sw", "sex"])
df["ww"] = np.random.randn(500)
df["sw"] = np.random.randn(500)
df["sex"] = np.random.choice(["M", "F", "I"], size=500)
clr = {'M':'firebrick','F':'blueviolet', 'I':'yellow'}
df["color"] = df["sex"].apply(lambda x: clr[x])
plt.scatter(df["ww"], df["sw"], color=df["color"], alpha=0.7)
或者,如果您不想要新列,或者字典在分散调用之间发生变化,您可以这样做
plt.scatter(df["ww"], df["sw"], color=df["sex"].apply(lambda x: clr[x]), alpha=0.7)
不确定是否有仅使用字典的更好解决方案,但鉴于您已经在 pandas 中拥有数据,我认为可以使用它。