使用Pandas和Matplotlib绘制多条折线图
为了使用Pandas和Matplotlib绘制多条折线图,我们可以按照以下步骤进行 −
- 设置图的大小,并调整子图之间和周围的内边距。
-
使用Pandas DataFrame类创建一个二维的、可能是异构的表格数据,其中列为 x、y 和 equation 。
-
按给定的索引,如x、 equation 和 y ,对重塑后的数据进行组织。
-
使用 plot() 方法绘制折线。
-
使用 show() 方法显示图像。
示例
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame([
["y=x^3", 0, 0],
["y=x^3", 1, 1],
["y=x^3", 2, 8],
["y=x^3", 3, 27],
["y=x^3", 4, 64],
["y=x^2", 0, 0],
["y=x^2", 1, 1],
["y=x^2", 2, 4],
["y=x^2", 3, 9],
["y=x^2", 4, 16],
["y=mx", 0, 0],
["y=mx", 1, 1],
["y=mx", 2, 2],
["y=mx", 3, 3],
["y=mx", 4, 3],
], columns=['equation', 'x', 'y'])
df = df.pivot(index='x', columns='equation', values='y')
df.plot()
plt. **show()**