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 Region
name. How do I get names on X-axis?
So far I tried:
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
ax = df[['Men','Women']].plot(kind='bar', title ="Population",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Areas",fontsize=12)
ax.set_ylabel("Population",fontsize=12)
plt.show()
Currently it shows x ticks as 0,1,2..
I had a lot of trouble finding an answer I really liked for this, the below function achieves it quite well, and is very adaptable,
Below is an example of my result, though I set a new color for each value in a separate column in the dataframe
My columns were titled ['A','B','C','D','E']
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) orax.set_xticklabels()
Regarding the rotation, the last two methods allow you to pass a rotation argument along with the labels. So something like:
should force them to lay horizontally.
plot.bar() method inherits its arguments from plot(), which has
rot
argument:from the docs:
it also uses per default index as ticks for x axis:
alternatively you can set index explicitly - it might be useful for multi-level indexes (axes):