如何在sagemath中添加标题、轴标签和图例?

2024-05-14 23:10:11 发布

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

我目前正在使用sagemath托管的在线工作簿制作一些图表。

这是我正在尝试生成图形的一些代码的示例:

myplot = list_plot(zip(range(20), range(20)), color='red')
myplot2 = list_plot(zip(range(20), [i*2 for i in range(20)]), color='blue')
combined = myplot + myplot2
combined.show()

这是非常基本的——基本上是两个相互并列的散点图。

是否有方法可以轻松地添加轴标签、图例和可选的标题?

我设法想出了一个解决方案,让我添加轴标签,但它看起来真的丑陋和愚蠢。

from matplotlib.backends.backend_agg import FigureCanvasAgg 
def make_graph(plot, labels, figsize=6):
    mplot = plot.matplotlib(axes_labels=labels, figsize=figsize)
    mplot.set_canvas(FigureCanvasAgg(mplot))
    subplot = mplot.get_axes()[0]
    subplot.xaxis.set_label_coords(x=0.3,y=-0.12)
    return mplot

a = make_graph(combined, ['x axis label', 'y axis label'])
a.savefig('test.png')

是否有更简单的方法添加轴标签、图例和标题?


Tags: 方法labelsplotrange标签ziplabellist
2条回答
  • 轴标签:myplot.xlabel("text for x axis")myplot.ylabel("text for y axis")
  • 标题:myplot.title("My super plot")
  • 图例:在调用plot时添加label="Fancy plot"参数,并使用legend()创建图例

有关详细说明,请参见herethere

我最终找到了sagemath的Graphics对象的the documentation

我不得不这样做:

myplot = list_plot(
    zip(range(20), range(20)), 
    color='red', 
    legend_label='legend item 1')

myplot2 = list_plot(
    zip(range(20), [i*2 for i in range(20)]), 
    color='blue', 
    legend_label='legend item 2')

combined = myplot + myplot2

combined.axes_labels(['testing x axis', 'testing y axis'])
combined.legend(True)

combined.show(title='Testing title', frame=True, legend_loc="lower right")

我不完全确定为什么没有title方法,也不知道为什么在不需要轴的情况下必须在show内指定标题,但这似乎确实有效。

相关问题 更多 >

    热门问题