Matplotlib散点图如何将指定年份列表对应数据点设为红色
解决方案
直接为每个散点指定对应颜色即可,无需额外分层绘制,从根源规避点位置、大小偏移问题,修改后的完整可运行代码如下:
import matplotlib.pyplot as plt from adjustText import adjust_text histo = [1949,1976,1990,1991] #此处为需要标红的年份列表 a, b, c, texts=[], [], [], [] year=[1970, 1971, 1974, 1976, 1978, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1996, 1997, 1998, 1999] meanYear={1970: 6.524064171122993, 1971: 11.934731934731936, 1974: 20.320855614973265, 1976: 5.925925925925922, 1978: 10.43478260869565, 1980: 4.242424242424238, 1981: 16.363636363636367, 1982: 17.748917748917748, 1983: 3.6363636363636394, 1984: 2.857142857142852, 1985: 12.855831037649216, 1986: 9.836829836829834, 1988: 17.045454545454547, 1989: 18.859784283513093, 1990: 21.346801346801346, 1991: 20.559440559440556, 1992: 15.75757575757576, 1993: 1.818181818181812, 1994: 6.363636363636365, 1996: 16.363636363636363, 1997: 10.267379679144385, 1998: 6.77685950413223, 1999: 7.27272727272728} sumDif={1970: 110.90909090909088, 1971: 465.4545454545455, 1974: 690.909090909091, 1976: 159.9999999999999, 1978: 239.99999999999994, 1980: 12.727272727272714, 1981: 98.1818181818182, 1982: 372.7272727272727, 1983: 18.181818181818198, 1984: 19.99999999999964, 1985: 1272.7272727272723, 1986: 383.6363636363635, 1988: 136.36363636363637, 1989: 1112.7272727272725, 1990: 1152.7272727272727, 1991: 534.5454545454545, 1992: 47.27272727272728, 1993: 7.272727272727248, 1994: 12.72727272727273, 1996: 49.09090909090909, 1997: 523.6363636363636, 1998: 74.54545454545453, 1999: 7.27272727272728} nbDay={1985: 99, 1989: 59, 2016: 55, 1990: 54, 1997: 51, 1971: 39, 1986: 39, 1974: 34, 1976: 27, 1991: 26, 1978: 23, 1982: 21, 1970: 17, 1998: 11, 1988: 8, 1984: 7, 1981: 6, 1983: 5, 1993: 4, 1980: 3, 1992: 3, 1996: 3, 2018: 3, 1994: 2, 1999: 1} # 生成颜色列表 colors = [] for key in year : pos_x= nbDay[key] pos_y=meanYear[key] size=sumDif[key] #标签 a.append(pos_x) b.append(pos_y) c.append(size) texts.append(plt.text(pos_x,pos_y,key)) # 同步判断当前年份对应散点颜色 colors.append('red' if key in histo else 'orange') d=[0.5*n for n in c] #点大小 plt.scatter(a,b,s=d,c=colors) adjust_text(texts,a,b) plt.xlabel("titlex") plt.ylabel("titley") plt.title("title") plt.show()
修改说明
- 仅新增了颜色匹配逻辑,其余原有绘制逻辑、adjustText标注逻辑完全不变,所有点同批次绘制,位置、大小和原版本完全一致,不会出现偏移问题
- 属于
histo列表的年份对应散点会自动标记为红色,其余保持橙色,1949不在提供的year列表中,因此不会生成对应红色点
内容的提问来源于stack exchange,提问作者Enola Henrotin
相关产品推荐
相关产品推荐

