python - 当我尝试设置 plt.axes() 时,matplotlib.pyplot plt.bar() 发出警告

标签 python matplotlib

我正在尝试生成一个简单的 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/

相关文章:

Python:numpy 数组子列表与序列很重要的大列表匹配

python - 使用 matplotlib : ImportError: No module named animation?

python 3 : matplotlib plotting four lines with dictionary

python - For循环遍历Python中的列表

python - 如何制作这些连续直方图/密度估计图

php - 我需要 mysql-client 来进行 PHP/Python 等交互吗?

python - 异步键盘中断和多线程

Python - 使用 latex 格式中断字符串

python - matplotlib 和seaborn : ValueError: Supply a 'c' kwarg or a 'color' kwarg but not both; they differ but their functionalities overlap

python - 在 Python 中使用 matplotlib.animation 的动画 3D 条形图示例