matplotlib 图例中的数字

发布于 2024-09-29 15:53:26 字数 345 浏览 2 评论 0原文

我有几行,我想展示一个图例。问题是,我无法使用不同的样式(--:-.),因为它们太少了,而且我无法使用标记(+* 等),因为我需要它们显示线上的一些点。

所以我想到的最好的主意就是使用数字。但我不知道如何用数字创造传奇​​。我什至可以自己在线条附近绘制数字(将它们放置在最佳位置),但是如何用数字绘制图例呢?

即而不是:

--  H
-.- Li

我想要类似的东西:

1  H
2  Li

I have a couple of lines and I want to show a legend. The problem is, I can't use different styles (--, :, -.) because there are too few of them, and I can't use markers (+, *, etc.) because I need them to show some points on the lines.

So the best idea I've come up with is to use numbers. But I can't figure how I can create legends with numbers. I can even draw numbers near lines myself (to place them in the best position), but how can I then draw a legend with the numbers?

I.e. instead of:

--  H
-.- Li

I'd like something like:

1  H
2  Li

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九局 2024-10-06 15:53:26

也许加入一点乳胶?

#In which we make a legend; not with lines, but numbers!

import pylab as pl
pl.rc('text', usetex=True)

pl.figure(1)
pl.clf()
ax = pl.subplot(111)
pl.plot(range(0,10), 'k', label = r'\makebox[25]{1\hfill}Bla')
pl.plot(range(1,11), 'k', label = r'\makebox[25]{12\hfill}Bla12')
lgd = pl.legend(handlelength = -0.4)
for k in lgd.get_lines():
k.set_linewidth(0)
pl.draw()
pl.show()

数字/标签通过使用具有特定宽度的 \makebox 和 \hfill 来对齐,以占用标签未使用的空间。数字不是自动的,但如果您使用循环来绘制线条,那么您可以添加一个计数器来跟踪数字。

不知道这是否是您要求的一部分,但通过将线宽设置为 0 并使图例中保留的空间为负数来删除线条。无法找到更简洁的方法来执行此操作,因为我相信图例始终意味着显示一条线(例如,您不能将 numpoints 设置为 0)。

当然,您也可以只在图中的正确位置添加一些文本,而根本不使用图例。

Perhaps a little Latex thrown into the mix?

#In which we make a legend; not with lines, but numbers!

import pylab as pl
pl.rc('text', usetex=True)

pl.figure(1)
pl.clf()
ax = pl.subplot(111)
pl.plot(range(0,10), 'k', label = r'\makebox[25]{1\hfill}Bla')
pl.plot(range(1,11), 'k', label = r'\makebox[25]{12\hfill}Bla12')
lgd = pl.legend(handlelength = -0.4)
for k in lgd.get_lines():
k.set_linewidth(0)
pl.draw()
pl.show()

The numbers/labels are aligned by using \makebox with specific width and \hfill to take up the space not used by your labels. Numbers are not automatic, but if you use a loop to draw your lines then you could add a counter to keep track of the numbers.

Don't know if this is part of your requirement, but the lines are removed by setting their linewidth to 0 and making the space reserved in the legend negative. Couldn't find a neater way of doing this as I believe a legend is always meant to show a line (e.g. you can't set numpoints to 0).

You could of course also just add some text in the right spot in your plot and not use a legend at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文