散点图绘制多组不同颜色的点

Scatterplot plot multiple groups of points with different colors

我想给字典的键涂上不同的颜色,请问怎么弄?

colors: {"Hardcover": "red", "Kindle Edition":"green", "Paperback":"blue", "ebook":"purple", "Unknown Binding":"black", "Boxed Set - Hardcover":"yellow"}
fig, ax = plt.subplots(figsize=(16, 8))

for key, value in colors.items():
         ax.scatter(data["Type"], data["Price"], c=value, label=key)

ax.legend()
plt.show()

您不必遍历颜色。您可以将其作为系列传递。

data = pd.DataFrame({'Type': ['Hardcover', 'Kindle Edition', 'Paperback'], 'Price': [1,2,3]})
colors = {'Hardcover': 'red', 'Kindle Edition':'green', 'Paperback':'blue'}
fig, ax = plt.subplots(figsize=(16, 8))

scatter_colors = data['Type'].map(colors)
ax.scatter(data['Type'], data['Price'], c=scatter_colors)

print(scatter_colors)
plt.show()

我认为您的情况不需要图例。如果你真的想要它,我认为唯一的方法可能是遍历 'Types'

由于 OP 需要图例而进行了编辑: 将上面代码块中的 scatter_colorsax.scatter 行替换为:

for book_type in data['Type'].unique():
    data_subset = data[data['Type'] == book_type].copy()
    ax.scatter(data_subset['Type'], data_subset['Price'], color=colors[book_type], label=book_type)
ax.legend()