使用Panda从CSV文件在python中绘制两列以上的列

时间:2016-09-30 06:57:12

标签: python pandas plot

我对python和编码很新。我有一个CSV文件,其第一行包含一系列飞行属性(即时间,速度,航向,电池电压等)。我希望能够绘制时间与速度对电池电压的关系。或电池电压与速度。我已经尝试了几个例子,但是,我看到的每个例子都是在CSV文件中绘制我不想要的所有内容。或者csv文件只有2列。

CSV File format:
time(ms), ground_speed, battery_voltage(v), airspeed(m/s)
1322,45,12,42
1342,64,11,60
1352,30,11,27

import pandas as pd
from pandas import DataFrame, read_csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')


df = pd.DataFrame.from_csv('myflight.csv', index_col=False)

df.plot(x='mSec', y='Airspeed(m/s)', color="g")
df.plot(x='mSec', y='AS_Cmd(m/s)', color="r")

我的问题在于它总是与第一个索引进行对比,这是时间。另外,我得到两个单独的图表。如何将空速和AS_Cmd加入到一个图形中,并能够在时间与其他东西之间绘制其他人?

3 个答案:

答案 0 :(得分:2)

当你是python的新手时,你可能应该开始放慢速度并首先尝试使用numpypandas是围绕numpy构建的库,希望您熟悉它。

我们可以稍微简化您的代码。我添加了一些评论来指导您完成。

# You do not need that many import statements, so we just import
# numpy and matplotlib using the common alias 'np' and 'plt'.
import numpy as np
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')

# Using numpy we can use the function loadtxt to load your CSV file.
# We ignore the first line with the column names and use ',' as a delimiter.
data = np.loadtxt('myflight.csv', delimiter=',', skiprows=1)

# You can access the columns directly, but let us just define them for clarity.
# This uses array slicing/indexing to cut the correct columns into variables.
time = data[:,0]
ground_speed = data[:,1]
voltage = data[:,2]
airspeed = data[:,3]

# With matplotlib we define a new subplot with a certain size (10x10)
fig, ax = plt.subplots(figsize=(10,10))

ax.plot(time, ground_speed, label='Ground speed [m/s]')
ax.plot(time, voltage, label='Voltage [V]')

# Show the legend
plt.legend()

此代码将在此处为您提供此图表:

enter image description here

参考

您可以找到NumPy reference中使用的功能的文档。

更新

澄清plt.subplots(figsize=(10,10))的用法:使用此命令创建一个新数字,但matplotlib想要返回多个值(在本例中为两个)。因此,您需要指定两个变量来接受它们。 fig保存图实例,ax将保存当前subplot。 一个数字可以有无限量的子图,所以你可以做如here所示的奇特事物。在上面的例子中,我们只定义了一个子图。

figsize属性以英寸为单位定义图的大小,因此得到的输出为10 x 10英寸。您可以使用值并查看输出。

答案 1 :(得分:1)

要直接解决您的问题而不要更深入,请执行以下操作:

subp = plt.figure().add_subplot(111)
df.plot(x='mSec', y='Airspeed(m/s)', color="g", ax=subp)
df.plot(x='mSec', y='AS_Cmd(m/s)', color="r", ax=subp)

您需要定义一个公共对象,用于绘制绘图并将其赋予绘图命令,否则每次绘制新绘图时都会创建。

答案 2 :(得分:1)

您只需设置所需的索引并一次性绘制所有内容:

import matplotlib

matplotlib.style.use('ggplot')

df.set_index('time(ms)')[['ground_speed','battery_voltage(v)']].plot(rot=0, figsize=(16,10))

enter image description here

相关问题