首页  >  文章  >  后端开发  >  动态扩展外轴图例的图形框:一种解决方案

动态扩展外轴图例的图形框:一种解决方案

Linda Hamilton
Linda Hamilton原创
2024-10-18 12:04:03160浏览

Dynamically Expanding Figure Box for Legends Outside Axes: A Solution

Dynamically Resizing Figure Box for Legends

When placing legends outside of the plot axes in Matplotlib, they can be cut off by the figure box. This issue arises when the legend length exceeds the axis size.

Avoidance of Axis Shrinking

Unlike other solutions, avoiding axis shrinking is preferred to maintain data visibility. Shrinking the axes reduces data readability, especially when dealing with complex plots with extensive legends.

Dynamic Figure Box Expansion

To dynamically expand the figure box to accommodate the legend, adjust the savefig call to the following:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')

where bbox_extra_artists considers additional artists (in this case, the legend) when determining the bounding box size.

Example Code

The following code generates a plot with a legend outside the axes and automatically resizes the figure box using bbox_extra_artists:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')

This code results in the plot with the legend outside the axes, and the figure box is dynamically adjusted to accommodate the legend size.

Conclusion

By utilizing the bbox_extra_artists parameter in savefig, you can dynamically expand the figure box to ensure that legends outside the axes are not cut off. This approach provides a convenient and effective solution without the drawbacks of axis shrinking.

以上是动态扩展外轴图例的图形框:一种解决方案的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn