这是我用来生成该图的代码
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)?
2- 在 y 轴上:我不想写所有的数字,只写几个。如何将其修复为:0.07、0.1、0.3、0.6?
3- 如何去除角落里的蜱虫?
编辑 1(问题 # 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')
关于python - 修复对数刻度中的 x 和 y 轴格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45248125/