如何更改 matplotlib 中轴标签的格式
How do I change the format of the axis label in matplotlib
如果我绘制对数比例图,matplotlib 会给我漂亮的条目 105、106、...
为了便于阅读,我更喜欢 1e5、1e6、...
的形式
我可以直接将轴属性设置为那样吗?
我相当丑陋的破解方法是:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 40, 100);
y = np.linspace(1, 5, 100);
# Actually plot the exponential values
plt.plot(x, 10**y)
ax = plt.gca()
ax.set_yscale('log')
# Rewrite the y labels
y_labels = ax.get_yticks()
ax.set_yticklabels(['1e%i' % np.round(np.log(y)/np.log(10)) for y in y_labels])
plt.show()
但肯定有更好的方法。
您使用ticker.FormatStrFormatter('%0.0e')
。这使用字符串格式 %0.0e
格式化每个数字,它表示使用指数表示法的浮点数:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = np.linspace(1, 40, 100)
y = np.linspace(1, 5, 100)
# Actually plot the exponential values
fig, ax = plt.subplots()
ax.plot(x, 10**y)
ax.set_yscale('log')
# Rewrite the y labels
y_labels = ax.get_yticks()
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0e'))
plt.show()
产量
如果我绘制对数比例图,matplotlib 会给我漂亮的条目 105、106、...
为了便于阅读,我更喜欢 1e5、1e6、...
的形式我可以直接将轴属性设置为那样吗?
我相当丑陋的破解方法是:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 40, 100);
y = np.linspace(1, 5, 100);
# Actually plot the exponential values
plt.plot(x, 10**y)
ax = plt.gca()
ax.set_yscale('log')
# Rewrite the y labels
y_labels = ax.get_yticks()
ax.set_yticklabels(['1e%i' % np.round(np.log(y)/np.log(10)) for y in y_labels])
plt.show()
但肯定有更好的方法。
您使用ticker.FormatStrFormatter('%0.0e')
。这使用字符串格式 %0.0e
格式化每个数字,它表示使用指数表示法的浮点数:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = np.linspace(1, 40, 100)
y = np.linspace(1, 5, 100)
# Actually plot the exponential values
fig, ax = plt.subplots()
ax.plot(x, 10**y)
ax.set_yscale('log')
# Rewrite the y labels
y_labels = ax.get_yticks()
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0e'))
plt.show()
产量