You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何用Pyplot绘制基于colorInfo着色的双变量多色曲线?

使用Matplotlib Pyplot实现按指定颜色绘制双曲线的方案

没问题,咱们一步步来实现这个需求,思路其实很清晰:先读入CSV数据,按颜色分组,再分别绘制对应颜色的曲线就行。下面是具体的实现步骤和完整代码:

1. 导入所需库

首先得用到pandas读取CSV文件,matplotlib.pyplot负责绘图,先导入它们:

import pandas as pd
import matplotlib.pyplot as plt

2. 读取并预处理CSV数据

你的CSV用|分隔,而且每个字段前后还有空格,所以读取的时候要指定分隔符,同时去掉多余的空格:

# 读取CSV,处理分隔符和空格
df = pd.read_csv('your_data.csv', sep='|', skipinitialspace=True)
# 可选:确认数据读取正确,打印前几行
print(df.head())

your_data.csv换成你实际的文件名即可,skipinitialspace=True会自动去掉|后面的空格,避免列名或数据带空格的问题。

3. 定义颜色映射关系

根据你说的colorInfo取值(0=蓝、1=红、2=绿),咱们创建一个字典来对应:

color_map = {0: 'blue', 1: 'red', 2: 'green'}

4. 分组绘制曲线

因为y1y2的取值范围差很大(0-150 vs -1-1),推荐用两个子图分别绘制,这样能更清晰地看到两条曲线的变化。如果硬要放在同一个图里,需要用双y轴,我后面也会提一下。

方案A:分两个子图绘制(推荐)

# 创建2行1列的子图,设置画布大小
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))

# 按color字段分组遍历
for color_code, group in df.groupby('color'):
    current_color = color_map[color_code]
    # 绘制y1的曲线
    ax1.plot(group['x'], group['y1'], color=current_color, 
             label=f'Color {color_code} ({current_color})')
    # 绘制y2的曲线
    ax2.plot(group['x'], group['y2'], color=current_color, 
             label=f'Color {color_code} ({current_color})')

# 设置第一个子图(y1)的样式
ax1.set_title('y1 Values vs x')
ax1.set_xlabel('x')
ax1.set_ylabel('y1')
ax1.legend()  # 显示图例
ax1.grid(True)  # 显示网格线

# 设置第二个子图(y2)的样式
ax2.set_title('y2 Values vs x')
ax2.set_xlabel('x')
ax2.set_ylabel('y2')
ax2.legend()
ax2.grid(True)

# 自动调整子图间距,避免重叠
plt.tight_layout()
# 显示图像
plt.show()

方案B:同一图中用双y轴绘制

如果想把两条曲线放在同一个图里,需要用双y轴来适配不同的取值范围:

fig, ax1 = plt.subplots(figsize=(10, 6))
color_map = {0: 'blue', 1: 'red', 2: 'green'}

# 先绘制y1在左轴
for color_code, group in df.groupby('color'):
    current_color = color_map[color_code]
    ax1.plot(group['x'], group['y1'], color=current_color, 
             label=f'y1 - Color {color_code}')

# 创建右轴用于绘制y2
ax2 = ax1.twinx()
for color_code, group in df.groupby('color'):
    current_color = color_map[color_code]
    ax2.plot(group['x'], group['y2'], color=current_color, linestyle='--', 
             label=f'y2 - Color {color_code}')

# 设置样式
ax1.set_title('y1 and y2 Values vs x')
ax1.set_xlabel('x')
ax1.set_ylabel('y1')
ax2.set_ylabel('y2')

# 合并两个轴的图例
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')

plt.grid(True)
plt.show()

这样就能完美实现你要的效果啦,运行代码后就能看到按指定颜色着色的两条曲线了。

内容的提问来源于stack exchange,提问作者ChrizZ

火山引擎 最新活动