【发布时间】:2021-11-03 07:22:53
【问题描述】:
我需要使用相同的函数绘制图形。
Y 轴刻度标签可以是 2 位,有时是 3 位整数。
虽然我将 y 轴刻度标签格式化为 3 位整数,但左侧脊柱前的间距略有变化。
如何为 y 轴刻度标签提供相同的空间,以便轴的左脊椎在不同图形的相同位置开始?
这里是复制这些数字的示例代码:
from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import MaxNLocator
import numpy as np
import os
def plot_figure(start, end, figure_name):
fwidth = 15
fheight = 7
fig = plt.figure(figsize=(fwidth, fheight), facecolor=None)
plt.style.use('ggplot')
# define margins
left_margin = 0.95 / fwidth
right_margin = 0.2 / fwidth
bottom_margin = 0.5 / fheight
top_margin = 0.25 / fheight
# create axes
x = left_margin # horiz. position of bottom-left corner
y = bottom_margin # vert. position of bottom-left corner
w = 1 - (left_margin + right_margin) # width of axes
h = 1 - (bottom_margin + top_margin) # height of axes
ax = fig.add_axes([x, y, w, h])
ax.set_facecolor('white')
# This code puts the edge line
for edge_i in ['left', 'bottom','right', 'top']:
ax.spines[edge_i].set_edgecolor("black")
ax.spines[edge_i].set_linewidth(3)
plus_minus = 50
x = np.arange(-plus_minus, plus_minus + 1, 1)
signal_array = np.random.randint(start, end + 1, size = 2*plus_minus+1)
plt.plot(x, signal_array, color='b', label='Signal', linewidth=2, zorder=10)
# This code puts the tick marks
plt.tick_params(axis='both', which='major', labelsize=50, width=3, length=10)
plt.tick_params(axis='both', which='minor', labelsize=50, width=3, length=10)
# This code provides the x and y tick marks and labels
plt.xticks(np.arange(-plus_minus/2, plus_minus/2+1, step=plus_minus/2), fontsize=50)
plt.xlim((-plus_minus, plus_minus))
ax.yaxis.set_major_formatter(FormatStrFormatter('%3d'))
ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2))
ax.yaxis.set_major_locator(MaxNLocator(3))
figure_file = os.path.join('/Users','burcakotlu','Desktop','test2.png')
fig.savefig(figure_file, dpi=100, bbox_inches="tight")
plt.close(fig)
plot_figure(20, 50, 'test1')
plot_figure(100, 130, 'test2')
【问题讨论】:
-
不要调用 bbox_inches="tight"。这为艺术家修剪了人物。
标签: python matplotlib yaxis