[英]Change matplotlib offset notation from scientific to plain
我想在我的繪圖中將y軸偏移的格式設置為非科學記數法,但我找不到設置來執行此操作。 其他問題及其解決方案描述了如何完全消除偏移量,或者將y-ticks設置為科學/普通符號; 我沒有找到設置偏移本身的符號的答案。
我已經嘗試過使用這兩個選項,但我認為它們是針對y-ticks而不是偏移量:
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
和
ax.get_yaxis().get_major_formatter().set_scientific(False)
所以,當我想要+6378.1
時,實際結果是+6.3781e3
+6378.1
有什么辦法嗎?
編輯:添加了示例代碼和圖:
#!/usr/bin/env python
from matplotlib import pyplot as plt
from matplotlib import ticker
plt.rcParams['font.family'] = 'monospace'
import random
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()
一種方法是禁用偏移文本本身並在其中添加自定義ax.text
,如下所示
from matplotlib import pyplot as plt
import random
plt.rcParams['font.family'] = 'monospace'
offset = 6378.1
Date = range(10)
R = [offset+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=offset)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
ax.yaxis.offsetText.set_visible(False)
ax.text(x = 0.0, y = 1.01, s = str(offset), transform=ax.transAxes)
plt.show()
您可以ScalarFormatter
默認的ScalarFormatter
並替換get_offset
方法,這樣它只會返回偏移量。 請注意,如果您想使其與乘法“偏移”兼容,則需要調整此解決方案(目前它只是打印警告)。
from matplotlib import pyplot as plt
import matplotlib.ticker
import random
class PlainOffsetScalarFormatter(matplotlib.ticker.ScalarFormatter):
def get_offset(self):
if len(self.locs) == 0:
return ''
if self.orderOfMagnitude:
print("Your plot will likely be labelled incorrectly")
return self.offset
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.yaxis.set_major_formatter(PlainOffsetScalarFormatter())
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.