我想知道如何执行以下操作:
我有一个DataFrame
点和类。我想绘制所有点并为每个类使用一种颜色。如何指定类如何引用图例中的颜色?
fig = plt.figure(figsize=(18,10), dpi=1600)
df = pd.DataFrame(dict(points1 = data_plot[:,0], points2 = data_plot[:,1], \
target = target[0:2000]))
colors = {1: 'green', 2:'red', 3:'blue', 4:'yellow', 5:'orange', 6:'pink', \
7:'brown', 8:'black', 9:'white'}
fig, ax = plt.subplots()
ax.scatter(df['points1'], df['points2'], c = df['target'].apply(lambda x: colors[x]))
答案 0 :(得分:1)
让图例为每种颜色设置单独条目(因此它是target
值)的最简单方法是为每个 target
值创建单独的绘图对象
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
target = np.random.randint(1,9, size=100)
df = pd.DataFrame(dict(points1=x, points2=y, target=target))
colors = {1: 'green', 2:'red', 3:'blue', 4:'yellow', 5:'orange', 6:'pink', \
7:'brown', 8:'black', 9:'white'}
fig, ax = plt.subplots()
for k,v in colors.items():
series = df[df['target'] == k]
scat = ax.scatter(series['points1'], series['points2'], c=v, label=k)
plt.legend()