首页 > 解决方案 > 如何在 matplotlib barh 图中更改宽度

问题描述

我的第一个列表中只有一条记录,第二个列表中该记录的计数。我需要将它们放在水平条形图中。列表 1 的 Y 轴值和列表 2 的值作为条形的标签。下面的代码给了我无法改变宽度的栏。我怎样才能改变宽度?这么大的宽度看起来很尴尬。如果不在 matplotlib 中,我可以使用其他一些 python 库来实现这一点吗?

import os
import cx_Oracle
import matplotlib.pyplot as plt

r_c = [Sales_report_2020]
a_i =  [1311]

 
# Figure Size
fig, ax = plt.subplots(figsize =(12, 8))
#replace the None with integer 0
b = [0 if x is None else x for x in a_i]
print(b)
 
# Horizontal Bar Plot
plt.barh(r_c,b,height=0.5)
plt.ylim(-0.5, len(b) - 0.5)
ax.tick_params(width=0.5,length=6)
 

 
# Add annotation to bars
for i in ax.patches:
    plt.text(i.get_width()+0.2, i.get_y()+0.27,
            "{:1.0f}".format(i.get_width()),
             fontsize = 10, fontweight ='bold',
             color ='grey') #str(round((i.get_width()), 2))
 
# Add Plot Title
ax.set_title('DTP!',
             loc ='center', )
 
# Add Text watermark
fig.text(0.9, 0.15, 'STPREPORT', fontsize = 12,
         color ='grey', ha ='right', va ='bottom',
         alpha = 0.7)
 
 
path = r"\\ssd.COM\View\Folder_Redirect\id\Documents\Conda_Envs"
 
os.chdir(path)
plt.savefig(path + '\BAR.png')
 
# Show Plot
plt.show()
conn.close()

在此处输入图像描述

标签: pythonmatplotlib

解决方案


和参数可以帮助你一点,但由于只有一个记录,width可能会自动调整绘图以使其看起来比你需要的更大。调整你的应该对你有帮助。我无法执行您的代码,因为我没有数据,但以下说明了我的意思:heightbarhmatplotlibylim

例如,

plt.barh(1311, width=0.01, height=0.01)

给你

示例一

尽管

plt.barh(1311, width=20, height=20)

给你

示例二

但是,如果你设置一个更好的ylim,你可以获得一个更好看的单杠。

plt.barh(1311, width=0.5, height=20)
plt.ylim([1200, 1400])

示例 3

当然,您可以编辑这些值以获得您想要的结果。


推荐阅读