【问题标题】:matplotlib invisible bar if height is zero如果高度为零,则 matplotlib 不可见条
【发布时间】:2013-08-07 21:40:27
【问题描述】:

我正在绘制一个没有轴的条形图。我只想显示具有非零值的条形图。如果它是零,我根本不想要酒吧。目前它会在零轴上显示一条细线,我希望它消失。我该怎么做?

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

data = (0, 1890,865, 236, 6, 1, 2, 0 , 0, 0, 0 ,0 ,0 ,0, 0, 0)
ind = range(len(data))
width = 0.9   # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, data, width)
plt.xlabel('Duration 2^x')
plt.ylabel('Count')
plt.title('DBFSwrite')
plt.axis([0, len(data), -1, max(data)])

ax = plt.gca()

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)

plt.savefig('myfig')

看到 x=0 和 x=7-16 处的细线了吗?我想消除那些。

【问题讨论】:

  • 你应该包括代码你到目前为止!
  • 好主意,我已经添加了代码和示例输出。

标签: matplotlib


【解决方案1】:

您可以利用numpy 的数组,并创建一个掩码,您可以使用它来过滤掉data 值为0 的索引。

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

data = np.array([0, 1890,865, 236, 6, 1, 2, 0 , 0, 0, 0 ,0 ,0 ,0, 0, 0])
ind = np.arange(len(data))
width = 0.9   # the width of the bars: can also be len(x) sequence

mask = data.nonzero()

p1 = plt.bar(ind[mask], data[mask], width)
plt.xlabel('Duration 2^x')
plt.ylabel('Count')
plt.title('DBFSwrite')
plt.axis([0, len(data), -1, max(data)])

ax = plt.gca()

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)

plt.savefig('myfig')

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2014-03-23
    • 2016-04-08
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多