从matplotlib中的.CSV文件制作多线图

use*_*693 8 csv matplotlib pandas

几周以来,我一直试图在.CSV文件的同一个图上绘制3组(x,y)数据,而我却无处可去.我的数据最初是一个Excel文件,我已将其转换为.CSV文件,并已pandas按照以下代码将其读入IPython:

from pandas import DataFrame, read_csv
import pandas as pd
# define data location
df = read_csv(Location)
df[['LimMag1.3', 'ExpTime1.3', 'LimMag2.0', 'ExpTime2.0', 'LimMag2.5','ExpTime2.5']][:7]
Run Code Online (Sandbox Code Playgroud)

我的数据采用以下格式:

Type    mag1    time1   mag2    time2   mag3    time3

M0      8.87    41.11   8.41    41.11   8.16    65.78;

...

M6     13.95  4392.03  14.41 10395.13  14.66 25988.32
Run Code Online (Sandbox Code Playgroud)

我试图在同一个情节上绘制time1vs mag1,time2vs mag2time3vs mag3,但是我得到了time..vs的情节Type,例如.代码:

df['ExpTime1.3'].plot()
Run Code Online (Sandbox Code Playgroud)

我得到'ExpTime1.3'(Y轴)作图M0M6(X轴),当我要的是'ExpTime1.3'VS 'LimMag1.3',与X-标签M0- M6.

  1. 如何获得'ExpTime..'vs 'LimMag..'图,同一图上的所有3组数据?

  2. 如何获取x轴上的M0- M6标签'LimMag..'值(也在x轴上)?

自从尝试askewchan的解决方案,由于未知的原因没有返回任何图表,我发现如果我将数据帧索引(df.index)更改为x轴的值,我可以得到ExpTimevs LimMag使用的图df['ExpTime1.3'].plot(),(LimMag1.3 ).但是,这似乎意味着我必须通过手动输入所需x轴的所有值来将每个所需的x轴转换为数据帧索引,以使其成为数据索引.我有太多的数据,这个方法太慢了,我只能一次绘制一组数据,当我需要在一个图上绘制每个数据集的所有3个系列时.有没有解决这个问题的方法?或者有人可以提供一个理由和解决方案,为什么II没有任何关于askewchan提供的解决方案的情节?

为了回应nordev,我再次尝试了第一个版本,没有产生任何情节,甚至没有空图.每次我输入其中一个ax.plot命令,我都会得到类型的输出: [<matplotlib.lines.Line2D at 0xb5187b8>],但是当我输入命令时plt.show()没有任何反应.当我plt.show()在askewchan的第二个解决方案中进入循环后,我得到一个错误回复说AttributeError: 'function' object has no attribute 'show'

我已经对原始代码做了一些调整,现在可以通过使索引与x轴(LimMag1.3)相同来得到ExpTime1.3vs LimMag1.3与代码的关系图df['ExpTime1.3'][:7].plot(),但我无法得到另外两组同一图上的数据.如果您有任何进一步的建议,我将不胜感激.我正在使用ipython 0.11.0通过Anaconda 1.5.0(64位)和spyder在Windows 7(64位)上,python版本是2.7.4.

sod*_*odd 11

如果我已经正确地理解了您,无论是这个问题还是您之前关于同一主题的问题,以下内容都应该是您可以根据自己的需求进行定制的基本解决方案.

几个子图:

请注意,此解决方案将在同一图上垂直输出与Spectral类(M0,M1,...)一样多的子图.如果您希望将每个Spectral类的图保存在单独的图中,则代码需要进行一些修改.

import pandas as pd
from pandas import DataFrame, read_csv
import numpy as np
import matplotlib.pyplot as plt

# Here you put your code to read the CSV-file into a DataFrame df

plt.figure(figsize=(7,5)) # Set the size of your figure, customize for more subplots

for i in range(len(df)):
    xs = np.array(df[df.columns[0::2]])[i] # Use values from odd numbered columns as x-values
    ys = np.array(df[df.columns[1::2]])[i] # Use values from even numbered columns as y-values
    plt.subplot(len(df), 1, i+1)
    plt.plot(xs, ys, marker='o') # Plot circle markers with a line connecting the points
    for j in range(len(xs)):
        plt.annotate(df.columns[0::2][j][-3:] + '"', # Annotate every plotted point with last three characters of the column-label
                     xy = (xs[j],ys[j]),
                     xytext = (0, 5),
                     textcoords = 'offset points',
                     va = 'bottom',
                     ha = 'center',
                     clip_on = True)
    plt.title('Spectral class ' + df.index[i])
    plt.xlabel('Limiting Magnitude')
    plt.ylabel('Exposure Time')
    plt.grid(alpha=0.4)

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

全部在相同的轴中,按行分组(M0,M1,...)

这是另一种解决方案,可以将所有不同的Spectral类绘制在相同的Axes中,并使用标识不同类的图例.这plt.yscale('log')是可选的,但是看看价值如何跨越如此大的范围,建议.

import pandas as pd
from pandas import DataFrame, read_csv
import numpy as np
import matplotlib.pyplot as plt

# Here you put your code to read the CSV-file into a DataFrame df

for i in range(len(df)):
    xs = np.array(df[df.columns[0::2]])[i] # Use values from odd numbered columns as x-values
    ys = np.array(df[df.columns[1::2]])[i] # Use values from even numbered columns as y-values
    plt.plot(xs, ys, marker='o', label=df.index[i])
    for j in range(len(xs)):
        plt.annotate(df.columns[0::2][j][-3:] + '"', # Annotate every plotted point with last three characters of the column-label
                     xy = (xs[j],ys[j]),
                     xytext = (0, 6),
                     textcoords = 'offset points',
                     va = 'bottom',
                     ha = 'center',
                     rotation = 90,
                     clip_on = True)

plt.title('Spectral classes')
plt.xlabel('Limiting Magnitude')
plt.ylabel('Exposure Time')

plt.grid(alpha=0.4)    
plt.yscale('log')
plt.legend(loc='best', title='Spectral classes')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

全部在相同的轴上,按列分组(1.3",2.0",2.5")

第三个解决方案如下所示,其中数据按系列(列1.3",2.0",2.5")而不是Spectral类(M0,M1,...)分组.这个例子与@非常相似askewchan的解决方案.一个区别是这里的y轴是一个对数轴,使得线条非常平行.

import pandas as pd
from pandas import DataFrame, read_csv
import numpy as np
import matplotlib.pyplot as plt

# Here you put your code to read the CSV-file into a DataFrame df

xs = np.array(df[df.columns[0::2]]) # Use values from odd numbered columns as x-values
ys = np.array(df[df.columns[1::2]]) # Use values from even numbered columns as y-values

for i in range(df.shape[1]/2): 
    plt.plot(xs[:,i], ys[:,i], marker='o', label=df.columns[0::2][i][-3:]+'"') 
    for j in range(len(xs[:,i])):
        plt.annotate(df.index[j], # Annotate every plotted point with its Spectral class
                     xy = (xs[:,i][j],ys[:,i][j]),
                     xytext = (0, -6),
                     textcoords = 'offset points',
                     va = 'top',
                     ha = 'center',
                     clip_on = True)

plt.title('Spectral classes')
plt.xlabel('Limiting Magnitude')
plt.ylabel('Exposure Time')

plt.grid(alpha=0.4)    
plt.yscale('log')
plt.legend(loc='best', title='Series')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


ask*_*han 3

pyplot.plot(time, mag)您可以在同一个图中调用三个不同的时间。给它们贴上标签是明智的。像这样的东西:

import matplotlib.pyplot as plt

...
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(df['LimMag1.3'], df['ExpTime1.3'], label="1.3")
ax.plot(df['LimMag2.0'], df['ExpTime2.0'], label="2.0")
ax.plot(df['LimMag2.5'], df['ExpTime2.5'], label="2.5")
plt.show()
Run Code Online (Sandbox Code Playgroud)

如果你想循环它,这会起作用:

fig = plt.figure()
ax = fig.add_subplot(111)
for x,y in [['LimMag1.3', 'ExpTime1.3'],['LimMag2.0', 'ExpTime2.0'], ['LimMag2.5','ExpTime2.5']]:
    ax.plot(df[x], df[y], label=y)
plt.show()
Run Code Online (Sandbox Code Playgroud)