【问题标题】:How do I change the format of the axis label in matplotlib如何更改 matplotlib 中轴标签的格式
【发布时间】:2015-06-04 16:08:17
【问题描述】:

如果我绘制对数比例图,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()

但肯定有更好的方法。

【问题讨论】:

  • tickerFormatStrFormatter 可能有某种方式

标签: matplotlib axis-labels


【解决方案1】:

您使用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()

产量

【讨论】:

  • 完美,正是我想要的。您不知道将1e+04 格式化为1e4 的方法吗?
  • 不幸的是,控制you would need to write a custom function。如果您确实想走这条路,请注意您可以使用ticker.FuncFormatter
  • 嗯,是的,我就是这么想的。不过还是感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多