python - 一次为 pandas 数据框中的 matplotlib 子图添加多个标签

标签 python pandas matplotlib

我在这里迷路了,可能混淆了 matplotlib 和 pandas 的功能。我有一个数据框,我想将其绘制在几个子图中以对相关数据进行分组。一切都按预期工作,但我无法让图例工作(如果我不使用子图,这会非常简单)。这是我的代码:

fig, (acceleration, rotation, rotationspeed) = plt.subplots(3, 1, sharex=True, figsize=(20,15))

acceleration.plot(params[['accX', 'accY', 'accZ']], label=['X', 'Y', 'Z'])
acceleration.set_title('Acceleration')
acceleration.set_ylabel('Acceleration (G)')
acceleration.grid(b = pref_grid_visible)
acceleration.legend()

rotation.plot(params[['roll', 'pitch', 'yaw']])
rotation.set_title('Rotation')
rotation.set_ylabel('Rotation angle (radians)')
rotation.grid(b = pref_grid_visible)

rotationspeed.plot(params[['rotX', 'rotY', 'rotZ']])
rotationspeed.set_title('Rotation speed')
rotationspeed.set_ylabel('Rotation speed (radians / second)')
rotationspeed.grid(b = pref_grid_visible)

# Set shared x label
fig.text(0.5, 0.1, 'Time (ms)')

标签不会自动从数据帧中读取,并且从matplotlib的文档中我了解到label应该包含一个字符串,这解释了为什么尝试显示X、Y和Z轴的加速度不起作用.

Example with wrong label setting

如何为每个子图正确设置 X、Y 和 Z 标签?

最佳答案

尝试

acceleration = params[['accX', 'accY', 'accZ']].plot(ax=acceleration)
#rest of code

您可以将轴传递给 df.plot ,它可以很好地处理图例,并且它返回您可以进一步操作的相同轴。

另一种方式是

acceleration.plot(params[['accX', 'accY', 'accZ']])
acceleration.legend(['X', 'Y', 'Z'])

关于python - 一次为 pandas 数据框中的 matplotlib 子图添加多个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30752562/

相关文章:

python - 是否有任何 pyspark 函数可以添加下个月,如 DATE_ADD(date, month(int type))

python - 子集 Pandas 数据框

python - 在哪里可以找到 matplotlib 中用于自定义的所有属性?

Python matplotlib - 如何为垂直线添加注释

使用 "print"语句的 Python IDLE 错误着色

python - tkinter 将小部件放入框架中

python-3.x - Pandas Dataframe 使用合并过滤结果。编码解码问题

python - 在 Pandas 中重新采样

python - 在 Pandas 中使用特定的图形处理程序

python - 我如何与假装成终端的子进程进行交互?