1

I am trying to create a horizontal bar chart with matplotlib. My data points are the following two arrays

distance = [100, 200, 300, 400, 500, 3000]
value = [10, 15, 50, 74, 95, 98]

my code to generate the horizontal bar chart is as follows

plt.barh(distance, value, height=75)
plt.savefig(fig_name, dpi=300)
plt.close()

The problem is my image comes out like this

https://i.stack.imgur.com/C2zGn.jpg

Is there a way to ensure all blocks are the same width and to skip the spaces in between 500 and 300

Sheldore
  • 37,862
  • 7
  • 57
  • 71
magladde
  • 614
  • 5
  • 23
  • how weird, in Python 2.7 it looks like this using your code: https://imgur.com/4o1mVxM. Broken axes are kind of a pain, e.g. [this](https://stackoverflow.com/questions/32185411/break-in-x-axis-of-matplotlib) question/answer – a11 Apr 08 '19 at 21:46

2 Answers2

1

You can do this making sure Matplotlib treats your labels like labels, not like numbers. You can do this by converting them to strings:

import matplotlib.pyplot as plt

distance = [100, 200, 300, 400, 500, 3000]
value = [10, 15, 50, 74, 95, 98]
distance = [str(number) for number in distance]
plt.barh(distance, value, height=0.75)

Note that you have to change the height.

Joooeey
  • 3,394
  • 1
  • 35
  • 49
1

Alternatively, you can use a range of numbers as y-values, using range() function, to position the horizontal bars and then set the tick-labels as desired using plt.yticks() function whose first argument is the positions of the ticks and the second argument is the tick-labels.

import matplotlib.pyplot as plt

distance = [100, 200, 300, 400, 500, 3000]
value = [10, 15, 50, 74, 95, 98]
plt.barh(range(len(distance)), value, height=0.6)
plt.yticks(range(len(distance)), distance)
plt.show()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71