Modifying axis labels for pandas bar plot

Viewed 2461

I'm having difficulties adding percentages to my y-ticks. My total plot area includes 2 different plots, one is plotting percentages (df1), the other is not (df2). I've tried a variety of solutions I've found here on stackoverflow and other sites, but haven't had any luck.


import pandas as pd

df1 = pd.DataFrame([80.18, 50.0, 72.3, 90.1, 87.7])
df2 = pd.DataFrame([1000, 2000, 3000, 4000, 5000])



fig, axes = plt.subplots(nrows=1, ncols=2)

df1.plot.bar(ax=axes[0], title = "this", figsize=(8,8), legend=False)

df2.plot.bar(ax=axes[1], title="that", figsize=(8,8), legend=False)

Any help is appreciated

2 Answers

You can make use of a PercentFormatter [matplotlib-doc] for the yaxis:

from matplotlib.ticker import PercentFormatter

fig, axes = plt.subplots(nrows=1, ncols=2)

subplot = df1.plot.bar(ax=axes[0], title = "this", figsize=(8,8), legend=False)
subplot.yaxis.set_major_formatter(PercentFormatter())

df2.plot.bar(ax=axes[1], title="that", figsize=(8,8), legend=False)

For the given sample data, this produces:

plot with PercentFormatter

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

df1 = pd.DataFrame([80.18, 50.0, 72.3, 90.1, 87.7])
df2 = pd.DataFrame([1000, 2000, 3000, 4000, 5000])

fig, axes = plt.subplots(nrows=1, ncols=2)

ax1 = df1.plot.bar(ax=axes[0], title = "this", figsize=(8,8), legend=False)
vals = ax1.get_yticks()
ax1.set_yticklabels(['{:.0%}'.format(x/100) for x in vals])


ax2 = df2.plot.bar(ax=axes[1], title="that", figsize=(8,8), legend=False)
vals2 = ax2.get_yticks()
ax2.set_yticklabels(['{:.0%}'.format(x/100) for x in vals2])

Picture

Related