python - 如何在 Matplotlib 中定义自定义轴?
问题描述
假设我有以下代码:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(520)
y = np.random.rand(520)
plt.plot(x, y)
这会产生以下图表:
如何定义自定义轴,使我的 X 轴如下所示:
解决方案
您可以使用:
plt.xscale('log')
将比例更改为对数比例set_major_formatter(ScalarFormatter())
将格式设置回正常(替换LogFormatter
)set_minor_locator(NullLocator())
删除次要刻度(也由对数刻度设置)set_major_locator(FixedLocator([...]
或plt.xticks([...])
在 x 轴上设置所需的刻度
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, NullLocator, FixedLocator
import numpy as np
x = np.arange(520)
y = np.random.uniform(-1, 1, 520).cumsum()
plt.plot(x, y)
plt.xscale('log')
# plt.xticks([...])
plt.gca().xaxis.set_major_locator(FixedLocator([2**i for i in range(0, 7)] + [130, 260, 510]))
plt.gca().xaxis.set_major_formatter(ScalarFormatter())
plt.gca().xaxis.set_minor_locator(NullLocator())
plt.show()
推荐阅读
- collections - 如何按其中一个字段索引一组记录?
- angular - 为复选框数组定义 [(ngModel)] 以使用表单获取不同 JSON 格式的输出
- node.js - 使用 NodeJS 更新 Active Directory 中的用户属性
- python - 即使对于 print() 超出 continue 块的某些行,也没有打印任何内容
- php - Wordpress 错误:“处理此指令时发生错误”。Debug.log 输出可用
- m4 - m4 可以执行用户定义的 bash 脚本吗?
- ios - 如何交换字符串数组中的第一项和第二项?
- asp.net - 如何水平显示 asp.net 验证摘要?
- javascript - 日期选择器范围不允许结帐日期为同一天
- dart - 为 ExpansionPanelList 的头部和主体赋予不同的颜色