我不能让它工作不标零。有什么推荐吗?谢啦,谢啦
statusMont = dfFinal[dfFinal.columns[0:1]]
valoresMont = dfFinal[dfFinal.columns[1:]]
dados = []
for itens in valoresMont.itertuples(index=False, name = None):
dados.append(itens)
values = dados
dadosKeys = []
for itens in statusMont.itertuples(index=False, name = None):
dadosKeys.append(itens[0])
keys = dadosKeys
dicts = {}
j = 0
for i in keys:
values = np.array(list(dados[j]))
dicts[i] = values
j+=1
print(dicts)
width = 0.6 # the width of the bars: can also be len(x) sequence
bottom = np.zeros(len(list(dados[0])))
fig, ax = plt.subplots()
for status, dict in dicts.items():
p = ax.bar(selecao, dict, width, label=status, bottom=bottom)
bottom += dict
ax.bar_label(p, label_type='center')
ax.set_title('Orçamentos - Por Montadora')
ax.legend()
plt.show()
个字符
Final Plot
嗨,我尝试了一些解决方案与np.nan建议在这里的stackoverflow,但我得到的错误:in _get_xy_transform引发RuntimeError(“未知返回类型”)RuntimeError:未知返回类型
2条答案
按热度按时间yyhrrdl81#
您可以只过滤掉Y(条形高度)为零的坐标。重写代码的后半部分:
字符串
我已经将
dict
更改为d
,因为dict
是一个保留字,如果您需要使用它,您可能会遇到问题。(你正在使它黯然失色,使它作为一个功能无法访问。它的作用是创建一个
numpy
布尔数组f
,基于一个布尔条件(d != 0
),我们可以使用它来索引numpy
数组selecao
和d
以选择值(使用布尔索引):型
有关更深入的解释,请参见https://numpy.org/doc/1.24/user/how-to-index.html
使用列表解析也可以降低效率(这是我最初的答案),这可能适合或帮助其他不使用
numpy
的人:型
这是使用
zip()
来重新组织数据,并将X坐标与元组中的Y坐标相关联:型
(The
list()
是必要的,因为zip()
返回适合迭代的对象,而不是列表。)我们重新组织数据,因为除了删除Y之外,我们还希望删除Y为零的X。它们必须一起掉下来。
然后我们使用一个列表解析(
[]
s)和一个条件/过滤器(if y
)来过滤掉Y为零的元组(X和Y)。一个列表解析的结果是一个迭代的项目列表(
for
),带有一个可选条件。所以这意味着为zip()
对象zip(selecao, d)
中的每个元组给予一个元组列表((x,y)
)。为了清楚起见,我可以使用
if y != 0
,但这是多余的,因为在布尔上下文中,零值的计算结果是False
。型
然后,我们使用两个列表解析再次分开X和Y:
型
这意味着
f
是一个元组的列表(迭代器),并迭代它们,忽略(_
)一个或另一个未使用的项,使用另一个项生成一个列表。注意:此解决方案可能不适合大量数据,因为它将
numpy
数据重新构造为列表,效率较低,但看起来您正在处理少量数据。我这样说是为了那些可能希望实现这个解决方案的人。8zzbczxx2#
为了避免使用Matplotlib在条形图中绘制零值,可以在绘制之前从数据中过滤掉零值。下面是一个例子:
字符串
在上面的示例中,
categories
列表表示条形图的类别,values
列表表示相应的值。我们迭代类别和值,过滤掉零值,并将非零类别和值存储在单独的列表中。然后,我们使用
plt.bar(non_zero_categories, non_zero_values)
和过滤的非零值绘制条形图。最后,我们分别使用
plt.xlabel()
、plt.ylabel()
和plt.title()
向图表添加标签和标题。plt.show()
函数显示图表。通过在绘制之前过滤掉零值,生成的条形图将仅显示非零值的条形图,从而有效地将零从图表中排除。