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://imgur.com/a/Q8dvHKR

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

Sheldore
  • 35,129
  • 6
  • 43
  • 58
magladde
  • 447
  • 3
  • 14
  • 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
  • 2,529
  • 1
  • 26
  • 37
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
  • 35,129
  • 6
  • 43
  • 58