Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming X-Axis Labels when using Matplotlib and Pandas

I'm running my code on iPython Notebooks, on a Macbook Pro Yosemite 10.10.4

I have a CSV file that I am trying to read using Python, and looking to come up with charts. The problem I am facing is renaming the X-Axis labels.

Essentially, the chart is trying to plot a count of different types of Audit Violations, but has really long descriptions of the said violations. For example:

  • Not approved by regional committee.......another 300 words - 17
  • No contract with vendor.......another 300 words - 14
  • Vendor Registration not on record.......another 300 words - 9

Instead of having these verbose reasons though, I would like to rename the X-Axis labels to just numbers or alphabets so that the graph reads somewhat like this:

  • A - 17
  • B - 14
  • C - 9

This is the code I have used, and except for the label names, I am happy with the result.

%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np 
import pylab as pl
pd.set_option('display.mpl_style', 'default') 
pd.set_option('display.width', 5000) 
pd.set_option('display.max_columns', 60)
plt.rcParams['figure.figsize'] = (15, 5)
fixed_data = pd.read_csv('audit-rep.csv',sep=',',encoding='latin1',index_col='Index', parse_dates=['Report Date'],dayfirst=False)

viol_counts = data['Audit Flag'].value_counts()
viol_counts[:10]
viol_counts[:10].plot(kind='bar')

I have tried to rename the x-axis labels using the code below.

 viol_counts.set_ylabel('No. of Violations')
 viol_counts.set_title('Audit Results')
 viol_counts.set_xticks(ind+width)
 viol_counts.set_xticklabels( ('A', 'B','C') )

This is the error I get when using the above code.

AttributeError: 'Series' object has no attribute 'set_ylabel'

I have come across a few other posts related to this issue, but not seen one that specifically addresses the renaming of individual labels. This isn't utterly important though, and I'm just trying to learn using python, and the actual work has been done in excel.

like image 764
user2762934 Avatar asked Oct 23 '25 09:10

user2762934


1 Answers

if you assign the plot Axes object to a variable name (here I've called it viol_plot), then you can perform action on that Axes object (you are currently trying to set the labels and ticks on the Series, not the plot):

viol_plot = viol_counts[:10].plot(kind='bar')

viol_plot.set_ylabel('No. of Violations')
viol_plot.set_title('Audit Results')
viol_plot.set_xticks(ind+width)
viol_plot.set_xticklabels( ('A', 'B','C') )
like image 72
tmdavison Avatar answered Oct 25 '25 22:10

tmdavison