如何在一个DataFrame中绘制多个数据列

  • Post category:Python

在一个DataFrame中绘制多个数据列,我们可以使用Matplotlib进行绘图。下面是详细的攻略过程。

准备数据

首先需要准备数据,我们使用pandas生成一个包含多个数据列的DataFrame,来模拟实际场景。

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": np.random.randn(100),
                   "B": np.random.randn(100),
                   "C": np.random.randn(100),
                   "D": np.random.randn(100)})

以上代码生成了一个包含4列随机数据的DataFrame,列名分别为A、B、C、D。

绘制多个数据列

接下来,我们使用Matplotlib进行数据绘制。首先需要导入相关的库。

import matplotlib.pyplot as plt

在绘图之前,我们要先创建一个图像对象,并设置图像的基本参数,如图像大小、标题等。

fig, ax = plt.subplots(figsize=(8, 6))  # 创建图像对象

ax.set_title("Multiple Data Columns")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.grid(True)  # 开启网格线

接下来,我们可以使用DataFrame的.plot()方法直接绘制多个数据列。

df.plot(x="A", y=["B", "C", "D"], ax=ax)

以上代码中,我们指定x轴绘制的数据列为A,y轴绘制的数据列为B、C、D,ax参数指定了图像对象,表示将绘制的图形添加到这个对象中。

最后,我们调用plt.show()方法显示绘制结果。

plt.show()

综合代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"A": np.random.randn(100),
                   "B": np.random.randn(100),
                   "C": np.random.randn(100),
                   "D": np.random.randn(100)})

fig, ax = plt.subplots(figsize=(8, 6))  # 创建图像对象

ax.set_title("Multiple Data Columns")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.grid(True)  # 开启网格线

df.plot(x="A", y=["B", "C", "D"], ax=ax)

plt.show()

执行以上代码,我们可以看到绘制出的图像,横轴为数据列A的数值,纵轴为数据列B、C、D的数值。图像中包含三条线段,分别对应B、C、D三个数据列的数值。