【问题标题】:Scatterplot plot multiple groups of points with different colors散点图绘制多组不同颜色的点
【发布时间】:2020-11-16 19:40:36
【问题描述】:

我想把字典的键画成不同的颜色,我怎么得到这个?

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

【问题讨论】:

  • 你的图片上传失败,你能解决吗?
  • 你好汤姆,我正在尝试修复错误,但我不能。剧情就是这样:i.stack.imgur.com/6emz0.png
  • ax.scatter(data["Type"], data["Price"], ...) 将一遍又一遍地绘制相同的数据。因此,散点图将完全重叠。

标签: python matplotlib paint scatter-plot


【解决方案1】:

您不必遍历颜色。你可以把它作为一个系列传入。

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

我认为您的情况不需要图例。如果你真的想拥有它,我认为唯一的方法可能是迭代“类型”

编辑因为 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()

【讨论】:

  • 非常感谢,正是我需要的。但我必须添加传说。我怎样才能得到它?
  • 编辑现在显示。我仍然觉得这有点毫无意义,因为 x 刻度标签在说同样的事情,但如果你愿意......
  • 非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 2015-03-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多