一次为 pandas 数据框中的matplotlib子图添加多个标签 [英] Adding multiple labels at once for matplotlib subplots from pandas dataframe
问题描述
我在这里迷路了,也许混淆了matplotlib和pandas功能.我有一个数据框,希望将其绘制在几个子图中以对相关数据进行分组.一切都按预期工作,但我无法使图例正常工作(如果我不使用子图,这将非常简单).这是我的代码:
I am getting lost here, maybe confusing matplotlib and pandas functionality. I have a dataframe that I want to plot in several subplots to group related data. Everything works as intended, but I cannot get the legend working (which is ridiculously simple if I do not use the subplots). Here is my code:
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 轴以进行加速不起作用.
Labels are not read automatically from the dataframe, and from matplotlib's documentation I understand that label
should contain a string, which explains why the attempt to display X, Y and Z axis for acceleration is not working.
如何为每个子图正确设置X,Y和Z标签?
How can I set X, Y and Z labels correctly for each subplot?
推荐答案
尝试
acceleration = params[['accX', 'accY', 'accZ']].plot(ax=acceleration)
#rest of code
您可以将轴传递给 df.plot
,它可以很好地处理图例,并返回可以进一步操作的相同轴.
You can pass an axis to df.plot
, which handles legends pretty well, and it returns the same axis which you can further manipulate.
另一种方式是
acceleration.plot(params[['accX', 'accY', 'accZ']])
acceleration.legend(['X', 'Y', 'Z'])
这篇关于一次为 pandas 数据框中的matplotlib子图添加多个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!