注释并在轴的侧面放置图例,多轴的特殊情况:

2024-09-29 21:53:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的问题。我希望从其他数据中绘制散点图,而不是在这个工作示例中,在同一个图形上,两个散点图具有两个不同的轴(每个轴的数据比例都很大)。 我几乎成功了,结果如下:

fig = plt.figure(figsize=(20, 10))
fig.tight_layout
ax = plt.axes()
ax_bis = ax.twinx()

x = np.linspace(-1,1,100)
y1 = dist1 = np.random.normal(0.5, 0.25, 100)
y2 = dist2 = np.random.normal(8, 0.1, 100)


plt.grid(True)
lns1 = ax.plot(x,y1, 'ro', label = 'dist 1' )
lns2 = ax_bis.plot(x,y2, 'yx', label = 'dist 2')


lns = lns1+lns2
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc = "upper left")

#plt.text(50, .025, r'$\mu=100,\ \sigma=15$')
#ax_bis.xlabel('Time')

plt.suptitle('my graph')

enter image description here

my struggle is with this : I can't name the axis. The classical ways don't function (I put them in the code as comments) and I would love to put some comments on the graph itself (like a small text saying : "hey ! the graph is great"). How could one do that ?


Tags: the数据npfigpltrandomaxlabel
1条回答
网友
1楼 · 发布于 2024-09-29 21:53:49

您已经非常接近设置标签和获取文本了

fig = plt.figure(figsize=(20, 10))
fig.tight_layout
ax = plt.axes()
ax_bis = ax.twinx()

x = np.linspace(-1,1,100)
y1 = dist1 = np.random.normal(0.5, 0.25, 100)
y2 = dist2 = np.random.normal(8, 0.1, 100)


plt.grid(True)
lns1 = ax.plot(x,y1, 'ro', label = 'dist 1' )
lns2 = ax_bis.plot(x,y2, 'yx', label = 'dist 2')


lns = lns1+lns2
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc = "upper left")

# EDITS
ax.set_xlabel('Time')
ax.text(0,0.6,"Hello World") # x,y,message
#plt.text(50, .025, r'$\mu=100,\ \sigma=15$')
#ax_bis.xlabel('Time')

plt.suptitle('my graph')

注意:您的绘图是一个

'AxesSubplot' object

并且不具有.xlabel属性,而是具有.setxlabel属性

可以使用(伪代码)设置文本

ax.text(xval,yval,message)

结果如下。 enter image description here

相关问题 更多 >

    热门问题