0

I wanted to create a bar chart from a employee survey using matplotlib. After following the directions on the following question

How to create a bar chart/histogram with bar per discrete value?

I came up with the code

satisfaction = survey['satisfaction'].value_counts().sort_index()
ax = satisfaction.plot(kind='bar')
fig = ax.get_figure()
fig.autofmt_xdate()
plt.show()

Which printed the following graph

bar chart of Satisfaction

So, from here.

1-How do I centralize the chart? I mean, I have a big space between the left border and the 1st column and no border at all between the last column and the right border. I want to have both spaces of the same size.

2-How do I change the columns labels? the "1" on the 1st column really means "Very Satisfied", the "2" mean "Satisfied" and so on. I want to put the word meanings instead of the numeric values.

3-How to I put the chart title and x and y axes labels.

1
  • side note: no need to call fig.autofmt_xdate(). you don't have date Commented Sep 21, 2014 at 1:08

1 Answer 1

1
  1. ax.set_xlim(left=..., right=...)
  2. Probably simplest to have those values in our dataframe and plot against those
  3. ax.set_xlabel(...) and ax.set_ylabel(...)

Note that 1 and 3 are demonstrated in most basic matplotlib tutorials.

Here's a good one: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html

For number 2, it's as simple as:

import numpy as np
import pandas
import matplotlib.pyplot as plt

datamap = {
    1: 'real bad',
    2: 'bad',
    3: 'meh',
    4: 'good',
    5: 'way good'
}


df = pandas.DataFrame(data=np.random.choice(range(1,6), size=37), columns=['score'])
df['rating'] = df.score.map(datamap.get)

fig, ax = plt.subplots()
df.rating.value_counts().plot(kind='bar', ax=ax)
## alternatively:
# df.groupby(by='rating').count().plot(kind='bar', ax=ax)
fig.tight_layout()

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

For question 2. in "R" I can get the same chart by by simple adding the argument 'names=c("my_text1","my_text2),..' to the bar chart code. It would be to cumbersome to having change all the data every time I just need a aesthetic change on the labels.
@user3724295 it's real not cumbersome at all. just different. see my edits with a short, self-contained, example.
Your method works, Thanks. However, I found that ax.set_xticklabels (('my_fancy_names')) can also do the trick.
@user3724295 the problem with that is that it's now your responsibility to keep the tick labels synchronized with the x-axis values and the dataframe. I prefer to make the computer do all of that work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.