自定义颜色散点图的Matplotlib图例

2024-05-29 05:43:37 发布

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

我是一个新手在这方面,并试图创建一个散点图与自定义气泡大小和颜色。这个图表显示得很好,但是我如何得到一个说明颜色所指的图例呢。就我所知:

inc = []
out = []
bal = []
col = []

fig=Figure()
ax=fig.add_subplot(111)

inc = (30000,20000,70000)
out = (80000,30000,40000)
bal = (12000,10000,6000)
col = (1,2,3)
leg = ('proj1','proj2','proj3')

ax.scatter(inc, out, s=bal, c=col)
ax.axis([0, 100000, 0, 100000])

ax.set_xlabel('income', fontsize=20)
ax.set_ylabel('Expenditure', fontsize=20)
ax.set_title('Project FInancial Positions %s' % dt)
ax.grid(True)
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)

这个线程很有用,但无法解决我的问题:Matplotlib: Legend not displayed properly


Tags: png颜色response图表figcolaxout
2条回答

也许这个example是有用的。

通常,图例中的项与某种打印对象有关。scatter函数/方法将所有圆视为单个对象,请参见:

print type(ax.scatter(...))

因此,解决方案是创建多个对象。因此,多次调用scatter

不幸的是,更新版本的matplotlib似乎没有在图例中使用矩形。因此,图例将包含非常大的圆,因为您增加了散点图对象的大小。

legend函数作为一个markerscale关键字参数来控制图例标记的大小,但它似乎被破坏了。

更新:

Legend guide建议在类似情况下使用Proxy ArtistColor API解释了有效的fc值。

p1 = Rectangle((0, 0), 1, 1, fc="b")
p2 = Rectangle((0, 0), 1, 1, fc="g")
p3 = Rectangle((0, 0), 1, 1, fc="r")
legend((p1, p2, p3), ('proj1','proj2','proj3'))

要获取以前在绘图中使用的颜色,请使用上面的示例,如:

pl1, = plot(x1, y1, '.', alpha=0.1, label='plot1')
pl2, = plot(x2, y2, '.', alpha=0.1, label='plot2')
p1 = Rectangle((0, 0), 1, 1, fc=pl1.get_color())
p2 = Rectangle((0, 0), 1, 1, fc=pl2.get_color())
legend((p1, p2), (pl1.get_label(), pl2.get_label()), loc='best')

此示例将生成如下绘图:

Matplotlib with custom legend

看看这个:

http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.legend

希望能有所帮助。如果不只是要求更多:)

相关问题 更多 >

    热门问题