user9108097
user9108097

Reputation:

First value of xticklabels missing when plotting a pandas DataFrame

I'm new to Pandas and matplotlib and want to plot this DataFrame

      season   won               team  matches    pct_won
0  2008/2009  28.0  Manchester United       38  73.684211
1  2009/2010  27.0  Manchester United       38  71.052632
2  2010/2011  23.0  Manchester United       38  60.526316
3  2011/2012  28.0  Manchester United       38  73.684211
4  2012/2013  28.0  Manchester United       38  73.684211
5  2013/2014  19.0  Manchester United       38  50.000000
6  2014/2015  20.0  Manchester United       38  52.631579
7  2015/2016  19.0  Manchester United       38  50.000000

Using these lines of code:

ax = aggregated_frame.plot(x='season', y='pct_won', figsize=(8,8), marker='o', rot=90, title='Performance by season of Team: {}'.format(aggregated_frame.iloc[0]['team']))
ax.set_xticklabels(aggregated_frame.season)
ax.set_xlabel('')
ax.yaxis.grid()
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
ax.legend(['Percentage of Matches Won'], fontsize=14)
for item in ([ax.title, ax.xaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(14);

But the first value of my xticklabels is removed in the resulting plot:

Result_By_Plotting

I tried several options, even just set ax.set_xticklabels([1,2,3,4,5,6,7,8]), but the first value is removed every time.

What is wrong here? Any help is more than welcome.

In addition: Why are the values of season not used as label in the first place? If I omit set_xticklabels no label is printed at all on the x-axis.

Upvotes: 11

Views: 5209

Answers (3)

mdrishan
mdrishan

Reputation: 511

The accepted answer did not work for me. I managed to move all my labels over by one through the following code. This allowed the first label to match with the first bar on my plot.

tick_labels = ['[0, 20)', '[20, 40)', '[40, 60)', '[60, 80)', '[80, 100)', '=100']
x_max = int(max(plt.xticks()[0]))  
plt.xticks(range(1, x_max), tick_labels) 

Upvotes: 0

Ab Bennett
Ab Bennett

Reputation: 1432

I had the same problem doing a heatmap. i tried the above but it cut off the edge rows and columns of my heatmap.

i did this to solve

l_col_list = list(df.columns.values)
ax1.set_xticklabels(['']+l_col_list,fontsize=6)
ax1.set_yticklabels(['']+l_col_list,fontsize=6)

Upvotes: 1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

You should never set the labels without setting the tick positions as well. I.e. if you use ax.set_xticklabels you always need to use ax.set_ticks as well (or else, there might be exceptions to this, in which case you need to know exactly what you're doing).

Here:

ax.set_xticks(range(len(df)))
ax.set_xticklabels(df.season)

produces

enter image description here

Upvotes: 17

Related Questions