[英]fix x and y axis format in log scale
這是我用來生成圖形的代碼
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# generate data
x = np.linspace(0.01, 9.9, 15)
y = np.linspace(0.07, 0.7, 15)
matplotlib.rcParams['font.size'] = 20
# legend
matplotlib.rcParams['legend.frameon'] = False
matplotlib.rcParams['legend.fontsize'] = 'medium'
# ticks
matplotlib.rcParams['xtick.major.size'] = 10.0
matplotlib.rcParams['xtick.minor.size'] = 5.0
matplotlib.rcParams['xtick.major.width'] = 2.0
matplotlib.rcParams['xtick.minor.width'] = 2.0
matplotlib.rcParams['xtick.major.pad'] = 8.0
matplotlib.rcParams['ytick.major.size'] = 10.0
matplotlib.rcParams['ytick.minor.size'] = 5.0
matplotlib.rcParams['ytick.major.width'] = 2.0
matplotlib.rcParams['ytick.minor.width'] = 2.0
matplotlib.rcParams['ytick.major.pad'] = 8.0
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111)
plt.scatter(x, y, marker='o', color='k')
plt.xscale('log')
plt.xlim(xmin=0.005, xmax=10)
plt.yscale('log')
plt.ylim(ymin=0.07, ymax=0.7)
plt.xlabel('x')
plt.ylabel('y')
# x axis format
ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%.2f"))
# y axis format
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%.1f"))
ax.yaxis.set_minor_formatter(matplotlib.ticker.FormatStrFormatter("%.1f"))
# borders
plt.axhline(0.07, color='k', lw=2)
plt.axhline(0.7, color='k', lw=2)
plt.axvline(0.005, color='k', lw=2)
plt.axvline(10, color='k', lw=2)
plt.show()
我有以下問題
1-如何解決x軸格式問題,以便最后2個數字應分別寫為1和10(而不是1.00和10.00)?
在y軸上的2:我不想寫所有的數字,只寫幾個。 如何將其固定為:0.07、0.1、0.3、0.6?
3-如何去除角落的壁虱?
如果您仔細看,在下圖中藍色矩形內,則角不平滑。 這是因為我使用plt.axhline
和plt.axvline
繪制了一條線(以使邊框變粗)。 這些線重疊繪制的角上的刻度線使角不平滑。 我的想法是去除角落的壁虱以使其光滑。 除非有我不知道的更聰明的方法。
對於問題1,您需要以下格式設置:
import matplotlib.ticker as ticker
def customizedLogFormat(x,pos):
decimalplaces = int(np.maximum(-np.log10(x),0))
formatstring = '{{:.{:1d}f}}'.format(decimalplaces)
return formatstring.format(x)
接着
ax.xaxis.set_major_formatter(ticker.FuncFormatter(customizedLogFormat))
對於您的問題2,我真的不知道實現目標的明智方法...但是經過一些測試,我認為'set_yticks'是實現此目標的一種可能方法:
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%.2f"))
#ax.yaxis.set_minor_formatter(matplotlib.ticker.FormatStrFormatter("%.2f"))
ax.set_yticks([0.07, 0.1, 0.3, 0.6])
ax.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
對於第3個問題,您可以通過以下代碼設置刻度位置:
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.