简体   繁体   English

如何在matplotlib中以像素为单位获取每个条的高度

[英]How to get the height of each bar in pixels in matplotlib

Is there a way to get the height of each bar in a barplot in matplotlib in pixels?有没有办法以像素为单位获取 matplotlib 中条形图中每个条的高度? 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]输出 [23, 17, 35, 29, 12]

在此处输入图片说明

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM