尽管来自不同的数据集,但我正在尝试制作格式相同的图,并且我遇到了获得一致的文本位置和适当的轴限制的问题,因为数据集的缩放比例不完全相同。例如 - 假设我生成了以下海拔剖面图:
import matplotlib.pyplot as plt
import numpy as np
Distance=np.array([1000,3000,7000,15000,20000])
Elevation=np.array([100,200,350,800,400])
def MyPlot(X,Y):
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.plot(X,Y)
fig.set_size_inches(fig.get_size_inches()*2)
ax.set_ylim(min(Y)-50, max(Y)+500)
ax.set_xlim(min(X)-50, max(X)+50)
MaxPoint=X[np.argmax(Y)], max(Y)
ax.scatter(MaxPoint[0], MaxPoint[1], s=10)
ax.text(MaxPoint[0], MaxPoint[1]+100, s='Maximum = '+str(MaxPoint[1]), fontsize=8)
MyPlot(Distance,Elevation)
然后我有另一个缩放比例不同的数据集:
Distance2=Distance*4
Elevation2=Elevation*5
MyPlot(Distance2,Elevation2)][2]][2]
由于第一个数据集中的单位变化比第二个数据集中的单位变化相对大得多,因此文本和轴标签没有按照我在第二个图中想要的格式进行格式化。有没有一种方法可以调整文本位置和轴限制以适应数据集的相对比例?
最佳答案
首先,要放置具有此类偏移量的文本,您几乎不想使用 text
。相反,请使用 annotate
。优点是您可以以点而不是数据单位给出文本的偏移量。
接下来,要减少刻度位置的密度,请使用 ax.locator_params
并更改 nbins
参数。 nbins
控制刻度密度。刻度位置仍将自动选择,但减少 nbins
将减少刻度位置的最大数量。如果您降低 nbins
,您可能还想更改 matplotlib 在选择刻度间隔时认为“偶数”的数字。这样,您就有更多选择来获得预期的报价单数。
最后,为避免使用设置的填充手动设置限制,请考虑使用 margins(some_percentage)
按当前限制的百分比填充范围。
显示所有的完整示例:
import matplotlib.pyplot as plt
import numpy as np
distance=np.array([1000,3000,7000,15000,20000])
elevation=np.array([100,200,350,800,400])
def plot(x, y):
fig, ax = plt.subplots(figsize=(8, 2))
# Plot your data and place a marker at the peak location
maxpoint=x[np.argmax(y)], max(y)
ax.scatter(maxpoint[0], maxpoint[1], s=10)
ax.plot(x, y)
# Reduce the maximum number of ticks and give matplotlib more flexibility
# in the tick intervals it can choose.
# Essentially, this will more or less always have two ticks on the y-axis
# and 4 on the x-axis
ax.locator_params(axis='y', nbins=3, steps=range(1, 11))
ax.locator_params(axis='x', nbins=5, steps=range(1, 11))
# Annotate the peak location. The text will always be 5 points from the
# data location.
ax.annotate('Maximum = {:0.0f}'.format(maxpoint[1]), size=8,
xy=maxpoint, xytext=(5, 5), textcoords='offset points')
# Give ourselves lots of padding on the y-axis, less on the x
ax.margins(x=0.01, y=0.3)
ax.set_ylim(bottom=y.min())
# Set the aspect of the plot to be equal and add some x/y labels
ax.set(xlabel='Distance', ylabel='Elevation', aspect=1)
plt.show()
plot(distance,elevation)
如果我们更改数据:
plot(distance * 4, elevation * 5)
最后,您可以考虑将注释放在轴顶部的正上方,而不是偏离点:
ax.annotate('Maximum = {:0.0f}'.format(maxpoint[1]), ha='center',
size=8, xy=(maxpoint[0], 1), xytext=(0, 5),
textcoords='offset points',
xycoords=('data', 'axes fraction'))
https://stackoverflow.com/questions/34321808/