1

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)')

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.

Example with wrong label setting

How can I set X, Y and Z labels correctly for each subplot?

2
  • what is params in your code? Can you make this a MWVE please? Commented Jun 10, 2015 at 9:48
  • Sorry, params is a (subset of) a dataframe. Commented Jun 10, 2015 at 10:29

1 Answer 1

3

Try

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

You can pass an axis to df.plot, which handles legends pretty well, and it returns the same axis which you can further manipulate.

Another way would be

acceleration.plot(params[['accX', 'accY', 'accZ']])
acceleration.legend(['X', 'Y', 'Z'])
Sign up to request clarification or add additional context in comments.

2 Comments

The second approach works like a charm... wondering why I did not try this :-)
Cool. I never used the labels param before so not sure what it's supposed to do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.