python - Matplotlib 将轴显示为二进制

标签 python python-2.7 matplotlib graphics

我试图用二进制而不是 Python 2.7 中的浮点值来标记图形的 x 轴。我正在尝试根据 documentation 使用 FormatStrFormatter('%b') Python Software Foundation 提供的应该可以工作。我还希望所有二进制字符串的字符长度相同。我也咨询过这个link .

我得到的错误是:

ValueError: unsupported format character 'b' (0x62) at index 1

我试过这样做:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%b'))
ax.yaxis.set_ticks(np.arange(0, 110, 10))

x = np.arange(1, 10, 0.1)
plt.plot(x, x**2)
plt.show()

最佳答案

您可以使用 StrMethodFormatter,这也适用于 b 选项。

StrMethodFormatter("{x:b}")

但是前导零需要知道您期望有多少(这里是 7)。

StrMethodFormatter("{x:07b}")

完整示例:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import StrMethodFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(StrMethodFormatter("{x:07b}"))
ax.yaxis.set_ticks(np.arange(0, 110, 10))

x = np.arange(1, 10, 0.1)
plt.plot(x, x**2)
plt.show()

enter image description here

关于python - Matplotlib 将轴显示为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446033/

相关文章:

python - 在 Python 中并行运行函数

python - 无法使用 cx_Freeze 进行编译

python - Flask RESTful POST JSON 失败

python - 在 GeoDjango 中导入空间数据时出错 - mpoly 字段的 KeyError

python - 如何在 Matplotlib 中的图框外绘制矩形

numpy - 为 Matplotlib 的 LineCollection 构建段列表

java - 什么是 "th"、 "python"、 "python3"、 "java"等...用于运行脚本的命令前面,称为?

python - Flask 应用程序不使用另一个模块中定义的路由

python - Odoo:创建新报价时如何更改默认搜索行为?

python - 绘制多个散点图 Pandas