Matplotlib散点图:按Priority指定对应颜色的实现方法
实现DataFrame散点图中Priority与预设颜色的精准绑定
问题背景
你需要基于包含多变量的DataFrame绘制散点图,具体要求:
- Y轴为
Price,X轴为Weight - 根据
Priority(取值1-10)为散点指定对应颜色,预设颜色列表为:
colors=["navy","lawngreen","red","green","purple","steelblue","orange","darkred","yellow","chocolate"]
其中Priority=1对应navy,Priority=2对应lawngreen,依此类推,但尝试用字典关联颜色时未成功。
解决方案
方法一:构建Priority到颜色的映射字典
通过字典明确绑定每个Priority值和对应颜色,逻辑清晰易维护:
import pandas as pd import matplotlib.pyplot as plt # 预设颜色列表 colors = ["navy","lawngreen","red","green","purple","steelblue","orange","darkred","yellow","chocolate"] # 生成映射字典:Priority值(1-10)对应颜色列表的对应项 color_mapping = {priority: colors[priority-1] for priority in range(1, 11)} # 为DataFrame添加颜色列 df['scatter_color'] = df['Priority'].map(color_mapping) # 绘制散点图 plt.scatter(x=df['Weight'], y=df['Price'], color=df['scatter_color']) plt.xlabel('Weight') plt.ylabel('Price') plt.show()
方法二:直接通过索引匹配颜色(更简洁)
利用Priority值减1得到颜色列表的索引,直接提取对应颜色,省去字典构建步骤:
import pandas as pd import matplotlib.pyplot as plt colors = ["navy","lawngreen","red","green","purple","steelblue","orange","darkred","yellow","chocolate"] # 直接通过列表索引获取对应颜色 plt.scatter( x=df['Weight'], y=df['Price'], color=[colors[priority-1] for priority in df['Priority']] ) plt.xlabel('Weight') plt.ylabel('Price') plt.show()
常见问题排查
如果之前用字典绑定失败,大概率是键值对不匹配:比如误将字典的键设为0-9(对应颜色列表索引),但你的Priority取值是1-10,导致无法匹配。只要确保字典的键是1-10,对应颜色列表的0-9索引位置即可解决。
内容的提问来源于stack exchange,提问作者nach
相关产品推荐
相关产品推荐

