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

4

我目前正在使用由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')

有没有更简单的方法来添加坐标轴标签、图例和标题?

3个回答

9

我最终找到了sagemath中的Graphics对象的文档

我需要这样做:

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 中指定,而轴则不需要,但这似乎可以正常工作。


关于为什么需要指定标题而不是轴,我想这只是因为数学家更习惯于没有标题的轴。标题选项在Sage中刚刚出现 - 请参见http://trac.sagemath.org/sage_trac/ticket/10512 - 因此我们很乐意考虑如何公开它的增强功能。 - kcrisman
更具体地说,Sage倾向于将有关绘图呈现的内容放在show中(这包括轴,其中axes=True是默认值),而实际上可以访问绘图本身和/或特定数据点,而无需绘制绘图,如果这有意义的话。 - kcrisman
1
您可以通过访问/修改 my_graphics_obj.SHOW_OPTIONS 字典来设置和查看稍后用于“show”命令的设置。 - Mark
1
对于坐标轴标签,可以使用 show(myplot,axes_labels=('$x$','$y$')) - 681234

0
这是一个将所有内容以直观的方式组合在一起的示例,首先定义图形属性,然后定义数据。
plus1 = [[1.1,6.7],[5.,20],[1.8,20],[2.3,12],[8.3,20],[29,34]]    
plus2 = [[1.1,8.9],[5,8.9],[3.9,6.7],[3.9,8.9],
            [5.0,12],[6.4,8.9],[1.4,12],[11,8.9],
            [14,12],[18,12]]
p=plot([],figsize=(4,4),title='Stable combinations of damping and segment length',frame=True,axes_labels= ['varPhi (damping)','w (segment length)'])
p += list_plot(plus2,color='blue',legend_label = 'most stable')
p += list_plot(plus1,color='red',legend_label = 'less stable')
show(p)

-1
  • 轴标签:myplot.xlabel("x轴文本")myplot.ylabel("y轴文本")
  • 标题:myplot.title("我的超级图表")
  • 图例:在plot的调用中添加一个label="花式图表"参数,并使用legend()创建图例

请参见此处那里以获取更多解释。


不幸的是,这并没有起作用——出现了一个异常,指出“xlabel”、“ylabel”和“title”不是图形对象(似乎与matplotlib略有不同)的成员。 - Michael0x2a
1
是的,Sage图形对象并不是matplotlib对象,尽管当我们保存一个对象(例如查看)时,我们在那里使用mpl。这使我们能够创建东西而不导入mpl,例如。 - kcrisman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接