如何用Matplotlib在同图中为两个列表设置不同绘图颜色
解决Matplotlib绘制两个列表曲线不同颜色的问题
你用extend把两个列表合并成一个后,plt.plot只能生成一条单一颜色的曲线,自然没法区分原始列表的部分。要实现不同颜色,核心思路是分别绘制两个原始列表,而不是合并后再画。下面提供两种常见场景的实现代码:
场景1:直接绘制两条独立曲线(x轴为各自的索引)
不需要合并列表,直接两次调用plt.plot,分别指定颜色即可:
import matplotlib.pyplot as plt list1= [0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4] list2=[2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4] # 绘制list1,指定蓝色 plt.plot(list1, color='blue', label='List 1') # 绘制list2,指定红色 plt.plot(list2, color='red', label='List 2') # 添加图例方便区分两条曲线 plt.legend() plt.show()
场景2:让两条曲线在x轴上连续衔接(list2接在list1之后)
如果希望list2的曲线从list1结束的位置开始,需要手动计算对应的x坐标:
import matplotlib.pyplot as plt list1= [0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4] list2=[2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4] # list1的x坐标范围:0到列表长度-1 x1 = range(len(list1)) # list2的x坐标从list1的长度开始,衔接上list1的结尾 x2 = range(len(list1), len(list1)+len(list2)) plt.plot(x1, list1, color='blue', label='List 1') plt.plot(x2, list2, color='red', label='List 2') plt.legend() plt.show()
补充说明
color参数可以用颜色名称(如'green'、'purple'),也可以用十六进制颜色值(如'#FF5733'),按需选择即可。- 添加
label并调用plt.legend()能让读者更清晰地分辨两条曲线对应的数据源。
内容的提问来源于stack exchange,提问作者Naj_m_Om
相关产品推荐
相关产品推荐

