我正在try 将两个文本框并排放在matplotlib图形的右上角.我关注了this tutorial on text-alignment,可以在右上角放置一个文本框.但我不知道如何添加第二个文本框,以使左上框的右边缘与右上框的左边缘相交.
输出运行最小工作示例的代码如下:
import numpy as np
import matplotlib.pyplot as plt
## data
x = np.linspace(
-10,
10,
51)
shrink_factors = np.linspace(
1,
0,
x.size)
y1 = shrink_factors * np.sin(
np.exp(
-1 * x))
y2 = shrink_factors * np.cos(
np.exp(
-1 * x))
## get plot parameters
xlim = [
np.min(x),
np.max(x)]
ylim = [
0,
1.125 * np.max([
np.max(y1),
np.max(y2)])]
facecolors = (
"red",
"blue")
(color1, color2) = facecolors
label1 = "Label 1"
label2 = "Label 2"
text1 = "RED 1"
text2 = "BLUE 2"
text_background_color = "gainsboro"
text_size = 12
figsize = (12, 7)
# figsize = (7, 12)
## initialize plot
fig, ax = plt.subplots(
figsize=figsize)
## plot data
ax.plot(
x,
y1,
color=color1,
label=label1)
ax.plot(
x,
y2,
color=color2,
label=label2)
ax.grid(
color="black",
linestyle=":",
alpha=0.3)
ax.set_xlim(
xlim)
ax.set_ylim(
ylim)
fig.legend(
mode="expand",
loc="lower center",
ncol=2)
## add text-boxes side-by-side
text_box1 = ax.text(
0.95,
0.95,
text1,
color=color1,
fontsize=text_size,
horizontalalignment="right",
verticalalignment="top",
transform=ax.transAxes)
text_box1.set_bbox({
"facecolor" : text_background_color,
"edgecolor" : "black"})
text_box1_pos = text_box1.get_position()
text_box2 = ax.text(
text_box1_pos[0],
0.95,
text2,
color=color2,
fontsize=text_size,
horizontalalignment="left",
verticalalignment="top",
transform=ax.transAxes)
text_box2.set_bbox({
"facecolor" : text_background_color,
"edgecolor" : "black"})
## finish plot
plt.show()
plt.close()
说