使用numpy和matplotlib进行gnuplot样式索引绘图 [英] gnuplot style index plotting using numpy and matplotlib

查看:59
本文介绍了使用numpy和matplotlib进行gnuplot样式索引绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到我记得我一直在使用gnuplot.最近我一直想切换到matplotlib.

I have been using gnuplot for as long as I remember. Recently i have been wanting to switch to matplotlib.

我经常使用的gnuplot的一项基本功能是索引"功能.

One basic function of gnuplot i frequently use is the 'index' function.

假设我有以下数据文件(foo.dat):

Suppose I have the following data file (foo.dat):

1 1
2 2
3 3


1 1
2 4
3 9

我可以做到:

plot 'foo.dat' index 0 u 1:2
replot 'foo.dat' index 1 u 1:2

以获得与同一图中的两个数据集相对应的两条线.一个人将如何使用numpy导入这样的文件并使用matplotlib对其进行绘制?

to get two lines corresponding to the two data sets in the same plot. How would one import such a file using numpy and plot it using matplotlib?

这是我希望我的最终情节看起来像的样子:

Here is how I would like my final plot to look like:

推荐答案

使用 genfromtxt 读取文件:

import numpy as np
import matplotlib.pyplot as plt

a = np.genfromtxt('foo.dat')

给予:

array([[ 1.,  1.],
       [ 2.,  2.],
       [ 3.,  3.],
       [ 1.,  1.],
       [ 2.,  4.],
       [ 3.,  9.]])

然后情节:

plt.plot(a[3:,0],a[3:,1],marker='x',color='g')
plt.plot(a[0:3,0],a[0:3,1],marker='x',color='r')

给出:

编辑

在@Cristoph的评论之后

Following @Cristoph's comment

要自动读取 ,如果使用 pandas 进行读取,则可以将文件拆分为多个块.但是您需要编写一个脚本来查找要跳过大文件的行.

To read in automatically, you could split the file into chunks, if you read in with pandas. But you'd need to write a script to find the rows to skip for a large file.

import pandas as pd
b=pd.read_csv('foo.dat',sep=' ',chunksize=3,header=None,skiprows=(3,4),index_col=0)
for c in b:
    plt.plot(c)

请注意 skiprows 参数-如果文件较长,则需要创建一个列表以适合您的文件.

Note the skiprows parameter - you'd need to create a list to fit your file if it's longer.

这篇关于使用numpy和matplotlib进行gnuplot样式索引绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆