0

I want to plot with data frames, but sometimes, I want more control over my x-tick labels and it looks like the data frame index is 'overruling' my code. here is the code:

test_df = pd.DataFrame({'cycles':[0,'b',3,'d','e','f','g'],'me':[100,80,99,100,75,100,90], 'you':[100,80,99,100,75,100,90], 'us':[100,80,99,100,75,100,90]})
f, ax = plt.subplots()
x = test_df['me']
x.index = ['a','b','c','d','e','f','g']



print(x)
for a in ax.get_xticklabels():
    a.set_text('me')

print(ax.get_xticklabels()[0])
ax.plot(x)
test_df.plot(x = 'cycles', y = 'me')

any idea on easier ways to easily modify x-tick labels for data frames easily without changing the index of the data frame, but easily just on the fly making the x-ticks whatever I want for any data frame column I want?

1
  • I.e. I want to set individual x-ticks, but I had to change the index in order to have the tick labels that I wanted, if I didn't, the index of the data frame would be the x-tick labels Commented Sep 11, 2018 at 16:02

1 Answer 1

1

You can specify the xticks within DataFrame.plot. This is basically just a dummy to ensure the number of tick labels is correct.

Then just set the tick labels manually after the plot.

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'cycles':[0,'b',3,'d','e','f','g'],
                   'me':[100,80,99,100,75,100,90]})

fig, ax = plt.subplots()
test_df.plot(x='cycles', y='me', ax=ax, xticks=test_df.index)
_ = ax.set_xticklabels(test_df['cycles'])
plt.show()

enter image description here

But you should be a bit hesitant of how the xticks aren't automatically generated. Line plots make sense when your values are ordinal. It doesn't seem obvious to me that 0 should be connected with 'b' anymore than 'e' should be connected to 'f'. In this situation a bar plot makes sense, and not-surprisingly, the xticks are generated without issue.

test_df.plot(x='cycles', y='me', kind='bar', legend=False)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

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.