我正在尝试生成一个简单的 pyplot 条形图,Python 3.6.0。代码如下:
import random
import matplotlib.pyplot as plt
import collections.Counter
#Generate random number of friends(0-19) for 100 users
num_freinds = [random.randrange(20) for _ in range(100)]
#Define a Counter to see how Friend Counts vary
c = Counter(num_freinds)
#Plot Friend Count vs Number of users with that Friend Count
xs = [i for i in range(20)]
ys = [c[i] for i in xs]
plt.bar(xs, ys)
plt.axes([-1, 20, 0, 12])
plt.xticks([i for i in range(21)])
plt.yticks([i for i in range(13)])
plt.xlabel("# of Friends")
plt.ylabel("Count of Users")
plt.show()
运行代码时出现以下错误:
\Python\lib\site-packages\matplotlib\axis.py:1035: UserWarning: 无法找到沿轴的像素距离以进行刻度间隔填充;假设不需要间隔填充。 warnings.warn(“无法找到沿轴的像素距离”
问题似乎出在以下代码行:
plt.axes([-1, 20, 0, 12])
如果我注释掉上面的行,一切正常,没有警告。
有人可以解释为什么设置轴似乎会导致像素警告吗?坐标轴范围与数据一致。我无法弄清楚这一点。
最佳答案
要调整要使用的轴限制 plt.axis
而不是plt.axes
。后者创建一个axes
对象,并将输入解释为指定位置的矩形(格式为[left,bottom,width,height]
),并且 -1
的像素位置位于图形之外,这导致了警告。
正确的代码是
plt.bar(xs, ys)
plt.axis([-1, 20, 0, 12])
关于python - 当我尝试设置 plt.axes() 时,matplotlib.pyplot plt.bar() 发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240430/