python - matplotlib 将 csv 标题行的图例添加到折线图

标签 python csv matplotlib legend

我的 result.csv 有 8 列,需要向我的折线图添加图例。我的代码是:

per_data=genfromtxt('result.csv',delimiter=',')
plt.plot(per_data)
plt.xlabel ('x stuff')
plt.ylabel ('y stuff')
plt.title('my test result')
plt.grid()
plt.show()

它给了我:

Result of 8 line graph 如何添加恰好是 csv 文件中标题行的图例?

最佳答案

如果您对 np.genfromtxt 使用 names=True 选项,它将在 .csv 的第一行中读取作为列名称。

例如:

import matplotlib.pyplot as plt
import numpy as np

# Make dummy csv file for this example
from io import StringIO 
result_csv = StringIO(u"""
xstuff, data1, data2, data3
0, 1, 2, 3
1, 1, 3, 4
2, 2, 1, 3
3, 1, 2, 5
""")

# Read in csv. Use names=True to also store column headers
per_data=np.genfromtxt(result_csv,delimiter=',',names=True)

# Loop over columns. Here I assume you have the x-data in the first column, so skip that one
for name in per_data.dtype.names[1:]:
    # Set the line's label to the column name
    plt.plot(per_data['xstuff'],per_data[name],label=name)

# Add a legend
plt.legend(loc=0)

plt.xlabel ('x stuff')
plt.ylabel ('y stuff')
plt.title('my test result')
plt.grid()
plt.show()

enter image description here

关于python - matplotlib 将 csv 标题行的图例添加到折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36877918/

相关文章:

Python参数解析器列表或元组的元组列表

python - 散布上的箭头

python - 在Python中绘制numpy数组的值

python - 迭代带有列表的字典以创建 n 个子图

Python turtle ondrag 事件与复合形状

Python Pandas 处理 308 请求

python - 具有不同方向的并排相同的 axis3d

python - 如何使用某些包含字符串的列在 pandas DataFrame 上绘制平行坐标?

python - 如何使用枚举包含 Jsonschema 多类型参数?

csv - 如何使用命令提示符将JMeter Aggregate Report结果保存到CSV文件?