python - Matplotlib 对数图 - 仅在 y 轴上显示 10 的幂
问题描述
假设我有以下代码:
import matplotlib as mpl
from matplotlib import pyplot as plt
x =[10, 14, 19, 26, 36, 50, 70, 98, 137, 191, 267, 373, 522, 730, 1021, 1429, 2000, 2800, 3919, 5486, 7680]
y = [ 0.0085, 0.006900000000000001, 0.007600000000000001, 0.007600000000000001, 0.01, 0.008700000000000003, 0.0094, 0.008800000000000002, 0.0092, 0.009, 0.009999999999999998, 0.010099999999999998, 0.010899999999999998, 0.010899999999999998, 0.011, 0.0115, 0.0115, 0.0118, 0.013000000000000001, 0.0129, 0.0131]
fig, ax1 = plt.subplots()
ax1.plot(x,y,linewidth=1)
ax1.set_xscale('log')
ax1.set_yscale('log')
plt.show()
结果如下:
我想要做的是删除 y 轴上不是10 的幂的刻度。在这个特定的例子中,删除 9x10^-3、8x10^-3 等,只保留 10^-2。
我尝试了其他一些建议,例如这个,但没有一个有效..有什么想法吗?
解决方案
您可以在最小和最大 y 值之间找到 10 的所有幂,然后使用 直接设置刻度ax1.set_yticks( y_ticks)
。
import matplotlib as mpl
from matplotlib import pyplot as plt
import math
x =[10, 14, 19, 26, 36, 50, 70, 98, 137, 191, 267, 373, 522, 730, 1021, 1429, 2000, 2800, 3919, 5486, 7680]
y = [ 0.0085, 0.006900000000000001, 0.007600000000000001, 0.007600000000000001, 0.01, 0.008700000000000003, 0.0094, 0.008800000000000002, 0.0092, 0.009, 0.009999999999999998, 0.010099999999999998, 0.010899999999999998, 0.010899999999999998, 0.011, 0.0115, 0.0115, 0.0118, 0.013000000000000001, 0.0129, 0.0131]
fig, ax1 = plt.subplots()
ax1.plot(x,y,linewidth=1)
ax1.set_xscale('log')
ax1.set_yscale('log')
ymin_pow = math.floor(math.log10(min(y)))
ymax_pow = math.ceil(math.log10(max(y)))
y_ticks = [10**i for i in range(ymin_pow, ymax_pow + 1)]
# optional: bound the limits
if y_ticks[0] < min(y):
y_ticks = y_ticks[1:]
if y_ticks[-1] > max(y):
y_ticks = y_ticks[-1:]
ax1.set_yticks(y_ticks, [str(i) for i in y_ticks])
# un-comment out the following line to have your labels
# not in scientific notation
# ax1.get_yaxis().set_major_formatter(mpl.ticker.ScalarFormatter())
plt.show()
推荐阅读
- c# - 我们可以在有和没有 jsonbody 的情况下重载 API
- javascript - 使用js移动对象时过渡不起作用
- python - 如何在 python 正则表达式中使用前瞻查找每个匹配项?
- javascript - 状态改变时报错【渲染方法应该是props和state的纯函数】
- arrays - 我可以将数组对象推送到 mongodb 上的空数组吗?(使用去)
- android - 删除 dispatchkeyevent 调用两次
- python - 给 numpy 数组 A 和是 MxN 和 B 这是 DxN 找到 AB=L2(A[i,:]-B[:,j]) 的欧几里德距离 st ijth 元素
- azure-logic-apps - For Each 中未显示逻辑应用迭代失败
- javascript - 类型上不存在属性:为什么 TypeScript 会抱怨而 JavaScript 没有?
- r - 在 R 中创建一个向量(关联数组)