numpy 如何在mathplotlib中使用条形图不绘制零

biswetbf  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(92)

我不能让它工作不标零。有什么推荐吗?谢啦,谢啦

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:未知返回类型

yyhrrdl8

yyhrrdl81#

您可以只过滤掉Y(条形高度)为零的坐标。重写代码的后半部分:

for status, d in dicts.items():
    f = d != 0
    p = ax.bar(selecao[f], d[f], width, label=status,  bottom=bottom)
    bottom += d
    ax.bar_label(p, label_type='center')

字符串
我已经将dict更改为d,因为dict是一个保留字,如果您需要使用它,您可能会遇到问题。(你正在使它黯然失色,使它作为一个功能无法访问。
它的作用是创建一个numpy布尔数组f,基于一个布尔条件(d != 0),我们可以使用它来索引numpy数组selecaod以选择值(使用布尔索引):

>>> x = np.arange(1,11)
>>> y = np.array([11,12,0,13,14,0,15,16,19,0])
>>> f = y != 0
>>> x[f]
array([1, 2, 4, 5, 7, 8, 9])
>>> y[f]
array([11, 12, 13, 14, 15, 16, 19])
>>> f
array([ True,  True, False,  True,  True, False,  True,  True,  True,
       False])


有关更深入的解释,请参见https://numpy.org/doc/1.24/user/how-to-index.html
使用列表解析也可以降低效率(这是我最初的答案),这可能适合或帮助其他不使用numpy的人:

for status, d in dicts.items():
    f = [ (x,y) for x,y in zip(selecao, d) if y ]
    p = ax.bar([ x for x,_ in f ], [ y for _,y in f ], width, label=status,  bottom=bottom)
    bottom += d
    ax.bar_label(p, label_type='center')

ax.set_title('Orçamentos - Por Montadora')
ax.legend()
plt.show()


这是使用zip()来重新组织数据,并将X坐标与元组中的Y坐标相关联:

>>> x = np.arange(1,11)
>>> y = np.array([1,2,0,3,4,0,5,6,9,0])
>>> x
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
>>> list(zip(x,y))
[(1, 1), (2, 2), (3, 0), (4, 3), (5, 4), (6, 0), (7, 5), (8, 6), (9, 9), (10, 0)]


(The list()是必要的,因为zip()返回适合迭代的对象,而不是列表。)
我们重新组织数据,因为除了删除Y之外,我们还希望删除Y为零的X。它们必须一起掉下来。
然后我们使用一个列表解析([] s)和一个条件/过滤器(if y)来过滤掉Y为零的元组(X和Y)。
一个列表解析的结果是一个迭代的项目列表(for),带有一个可选条件。所以这意味着为zip()对象zip(selecao, d)中的每个元组给予一个元组列表((x,y))。
为了清楚起见,我可以使用if y != 0,但这是多余的,因为在布尔上下文中,零值的计算结果是False

>>> f=[ (x,y) for x,y in zip(x,y) if y ]
>>> f
[(1, 1), (2, 2), (4, 3), (5, 4), (7, 5), (8, 6), (9, 9)]


然后,我们使用两个列表解析再次分开X和Y:

>>> [ x for x, _ in f ]
[1, 2, 4, 5, 7, 8, 9]
>>> [ y for _, y in f ]
[1, 2, 3, 4, 5, 6, 9]


这意味着f是一个元组的列表(迭代器),并迭代它们,忽略(_)一个或另一个未使用的项,使用另一个项生成一个列表。
注意:此解决方案可能不适合大量数据,因为它将numpy数据重新构造为列表,效率较低,但看起来您正在处理少量数据。我这样说是为了那些可能希望实现这个解决方案的人。

8zzbczxx

8zzbczxx2#

为了避免使用Matplotlib在条形图中绘制零值,可以在绘制之前从数据中过滤掉零值。下面是一个例子:

import matplotlib.pyplot as plt

# Example data
categories = ['A', 'B', 'C', 'D', 'E']
values = [0, 10, 20, 0, 30]

# Filter out zero values
non_zero_categories = []
non_zero_values = []
for cat, val in zip(categories, values):
    if val != 0:
        non_zero_categories.append(cat)
        non_zero_values.append(val)

# Plot the bar chart with non-zero values
plt.bar(non_zero_categories, non_zero_values)

# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart without Zero Values')

# Show the plot
plt.show()

字符串
在上面的示例中,categories列表表示条形图的类别,values列表表示相应的值。我们迭代类别和值,过滤掉零值,并将非零类别和值存储在单独的列表中。
然后,我们使用plt.bar(non_zero_categories, non_zero_values)和过滤的非零值绘制条形图。
最后,我们分别使用plt.xlabel()plt.ylabel()plt.title()向图表添加标签和标题。plt.show()函数显示图表。
通过在绘制之前过滤掉零值,生成的条形图将仅显示非零值的条形图,从而有效地将零从图表中排除。

相关问题