2

A similar question has been raised :

how to force matplotlib to display only whole numbers on the Y axis

I am trying to do exactly the same for a bar plot. My problem is that the bar object does not unpack to fig, ax. Here is the code :

import matplotlib.pylab as plt
x = [0, 0.5, 1, 2, 3, 3.5, 4, 4.5, 5, 7.5, 8.5,9]
y = [1,2,2,3,1,2,2,2,2,1,1,0]
width = 0.5
plt.bar(x, y, width, color="pink")
plt.xlabel('score')
plt.ylabel('antall')
plt.show()

And the bar graph :

A bar graph

I would like to only display whole integers on y-axis and the opposite on the x-axis (i.e numbers 0 to 10 with 0.5 increment).

tmdavison
  • 64,360
  • 12
  • 187
  • 165
imranal
  • 656
  • 12
  • 35

1 Answers1

5

You can use fig = plt.gcf() and ax = plt.gca() to get references to the current figures and axes objects.

However, using the matplotlib object-oriented interface always gives you have access to fig and ax and makes the code clearer which figure and axes you are controlling.

Also, you can use the matplotlib.ticker module for more control over tick locations. In this case, a MultipleLocator will do the trick to set the tick locations on multiples of 1 for the yaxis and 0.5 for the xaxis.

import matplotlib.pylab as plt
import matplotlib.ticker as ticker

x = [0, 0.5, 1, 2, 3, 3.5, 4, 4.5, 5, 7.5, 8.5,9]
y = [1,2,2,3,1,2,2,2,2,1,1,0]

fig, ax = plt.subplots(1)

width = 0.5
ax.bar(x, y, width, color="pink")
ax.set_xlabel('score')
ax.set_ylabel('antall')

ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

plt.show()

enter image description here

tmdavison
  • 64,360
  • 12
  • 187
  • 165