1

Is there a way to get the height of each bar in a barplot in matplotlib in pixels? I can easily get values In a list but actually I need the height of the bars to be in pixels. My output should be the containing list of heights of each bar in pixels and a plot. Is it possible?

Here is reproducible example:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.bar(langs,students)
hth = []
for i in ax.patches:
    hth.append(i.get_height())
print(hth)
plt.show()

Output [23, 17, 35, 29, 12]

enter image description here

m1k1
  • 143
  • 1
  • 2
  • 13
  • 2
    Does this answer your question? https://stackoverflow.com/questions/13714454/specifying-and-saving-a-figure-with-exact-size-in-pixels – meph Jan 13 '20 at 22:13
  • 1
    Your code returns the `height`, but the question text asks about the `width`. Which one is it? Also, what exactly do you need the values in pixels for? Unless you also know the position, it might not be too useful? – ImportanceOfBeingErnest Jan 13 '20 at 22:19
  • Than you for noticing. I edited my question. I need height not width. I need those heights in pixels because I am making a custom barplot in photoshop and i want to keep the same ratio if it is possible. – m1k1 Jan 13 '20 at 22:28

1 Answers1

4

There are many possible ways to get the bar height in pixels. One option is to draw the canvas, then use the window extent of the bars:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
bars = ax.bar(langs, students)
fig.canvas.draw()
r = fig.canvas.get_renderer()
heights = [bar.get_window_extent(r).height for bar in bars]
print(heights)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712