Volatil3 Volatil3 - 5 months ago 32
Python Question

Python Pandas: How to set Dataframe Column value as X-axis labels

Say I have data in following format:

Region Men Women
City1 10 5
City2 50 89

When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of
name. How do I get names on X-axis?

So far I tried:

import pandas as pd
import matplotlib.pyplot as plt
ax = df[['Men','Women']].plot(kind='bar', title ="Population",figsize=(15,10),legend=True, fontsize=12)

Currently it shows x ticks as


Since you're using pandas, it looks like you can pass the tick labels right to the DataFrame's plot() method. (docs). (e.g. df.plot(..., xticks=<your labels>))

Additionally, since pandas uses matplotlib, you can control the labels that way.

For example with plt.xticks() (example) or ax.set_xticklabels()

Regarding the rotation, the last two methods allow you to pass a rotation argument along with the labels. So something like:

ax.set_xticklabels(<your labels>, rotation=0)

should force them to lay horizontally.