Matplotlib显示错误 - 窄条和扭曲的轴

时间:2014-01-23 17:16:46

标签: python matplotlib bar-chart

我是一个新手,但已设法将一些代码放在一起,从csv制作一个简单的条形图。我有两组数据,我可以绘制其中一组好,但是当绘制另一组(这是一个几乎相同的数据集)时,它看起来不正确。数据基本上是两列,一列是频率值,另一列是文本。文本是该频率的bin范围,写的类似于[10。 20.]。为了绘制这些数据,我把它作为一个字符串读取并获取第一个值,将其转换为浮点数(参见代码),它非常适合给我两个值列表!!

然后我拿这两个列表,一个频率和一个'箱子'并绘制它们但我最终得到的是真正的窄条(基本上是线条)和一个频率,其中值显示为1e ^ 7(即3而不是30000000) ),但是x轴显示正常。

我的代码是:

import csv
import numpy as np
import matplotlib.pyplot as plt

inputfile = 'filename'

values = []
bins = []

fh = open(inputfile, 'r+')
for line in fh:
    values.append(float(line.split(',')[0]))
    bins.append(float(line.split(',')[1].replace('[','').replace(']','').strip().split(' ')[0]))

ticks = np.arange(0, 105000, 5000)

plot = plt.bar(bins, values, color='b', alpha=1, width=1)

plt.xlabel('distance (m)')
plt.ylabel('Frequency')
plt.xticks(ticks, rotation=90)
plt.show()

我会张贴我的情节照片,但我没有足够的代表点。

我的其他数据几乎与此相同,并且运行正常。

非常感谢任何帮助,

由于

1 个答案:

答案 0 :(得分:2)

听起来您将条形宽度设置为1,但指定间距非常大的位置。

例如,听起来你正在做这样的事情:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977) # Generate same random numbers each time

bins = np.arange(0, 10000, 100)
values = 3e7 * np.random.random(100)

plt.bar(bins, values, width=1)
plt.margins(0.05, 0) % Just for nicer display

plt.show()

enter image description here

问题在于您指定的是width=1。据推测,你宁愿让酒吧占据垃圾箱的整个宽度。

如果你有规则间隔的箱子,那么只需指定它们的间距。 (例如width = 1000等)。

如果它们没有经常间隔,那么请执行以下操作:

# From looking at your code, "bins" and "values" are the same length.
# Therefore, the width of the last (or first) bar is undefined.
# We'll assume that the width of the last bar is the same as the one before it
diff = np.diff(bins)
widths = np.hstack([diff, diff[-1]])

然后用plt.bar(bins, values, width=widths)

绘图

enter image description here

最后,如果您不希望科学记数法用于大值,最简单的方法是将axes.formatter.limits rc参数设置为更大的值。 (默认情况下,将使用科学记数法显示任何>= 1e7。)

作为一个完整的例子:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977)

# Generate data
bins = np.arange(0, 10000, 100)
values = 3e7 * np.random.random(100)

# Don't use scientific notation
plt.rcParams['axes.formatter.limits'] = [-100, 100]

# Plot...
plt.bar(bins, values, width=100)
plt.margins(0.05, 0)
plt.show()

enter image description here