0

Is it possible to format the tick labels in a pandas.DataFrame.plot() without importing the matplotlib.ticker library?

I've come to realise that pandas has many native functions I'm unaware of and I like to use them where possible — if only to simplify my code. And yes, pandas leans on matplotlib anyway, but I want to know to what extent I can style plots without directly invoking matplotlib functions.

For example, can I change the tick labels on this chart to percentages without matplotlib.ticker.Percentformatter()?

import pandas as pd
import numpy as np
import matplotlib as plt

df = pd.DataFrame(columns=["value"], data=np.random.rand(5))
ax = df.plot.barh()
ax.xaxis.set_major_formatter(plt.ticker.PercentFormatter(1))
plt.show()

bar pot

1 Answer 1

1

You can set a custom function as a string formatter with set_major_formatter.

For example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(columns=["value"], data=np.random.rand(5))
ax = df.plot.barh()
func = lambda x, pos: f"{int(x*100)}%"
ax.xaxis.set_major_formatter(func)
plt.show()

Figure

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

5 Comments

... but (note to OP), this is re-inventing the wheel.
@BigBen, it's a straightforward answer but, yes, it's not less effort/code. I was wondering whether pandas has its own tick formatting functions/methods.
@Markus - note that ax.set_major_formatter is matplotlib, not pandas.
@BigBen, yes. I'd prefer a pandas-only solution, but it might not exist.
@Markus I am quite sure pandas does not provide any convenient function/plotting parameter for this. I believe this is as simple as it can get: ax.xaxis.set_major_formatter('{x:.0%}')

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.