python - 如何在 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()
解决方案
和参数可以帮助你一点,但由于只有一个记录,width
可能会自动调整绘图以使其看起来比你需要的更大。调整你的应该对你有帮助。我无法执行您的代码,因为我没有数据,但以下说明了我的意思:height
barh
matplotlib
ylim
例如,
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])
当然,您可以编辑这些值以获得您想要的结果。
推荐阅读
- c# - Jquery.ajax 将 null 发送到控制器,但使用硬编码的变量
- web-services - SoapUI 中的转储文件是什么格式的?
- c - 在循环读取和写入一次后,我无法使用管道的写入和读取功能
- python - time.sleep 使 tkinter 崩溃还有什么我可以使用的吗
- c# - 我的 swipeview 没有首先以编程方式打开
- selenium - 从通知登录消息中获取文本
- c# - 我可以使用 C# 9 记录作为 IOptions 吗?
- c++ - C++ 无法正确运行输出
- php - 为什么我收到状态代码:WP Ajax 出现 400 Bad Request 错误?
- regex - 仅匹配已定义标签的属性