我是这方面的新手,但已经设法将一些代码放在一起,从 csv 制作一个简单的条形图。我有两组数据,我可以正常绘制其中一组数据,但在绘制另一组数据(几乎相同的数据集)时,它看起来不正确。数据基本上是两列,一列包含频率值,另一列包含文本。文本是该频率的 bin 范围,写法类似于 [10. 20.]。为了绘制这些数据,我将其作为字符串读取并获取第一个值,将其转换为 float (参见代码),这非常适合为我提供两个值列表!!
然后,我将这两个列表(一个频率和一个“箱”)绘制出来,但最终我得到了非常窄的条形图(基本上是线条)和一个频率,其中值按 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,但指定的位置间隔非常宽。
例如,听起来您正在做这样的事情:
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()
问题是您指定 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)
绘图
最后,如果您不希望对大值使用科学记数法,最简单的方法就是设置 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()
关于python - Matplotlib 显示错误 - 窄条和扭曲的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21315040/