【问题标题】:How to add titles, axis label, and legend in sagemath?如何在 sagemath 中添加标题、轴标签和图例?
【发布时间】:2012-09-29 05:32:48
【问题描述】:

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

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

【问题讨论】:

    标签: python graphing sage


    【解决方案1】:

    我最终为 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 中指定标题,而轴不必是,但这似乎确实有效。

    【讨论】:

    • 至于为什么必须指定标题而不是坐标轴,我想这只是因为数学家更习惯于没有标题的坐标轴。标题选项几乎没有出现在 Sage 中 - 请参阅 trac.sagemath.org/sage_trac/ticket/10512 - 所以我们很乐意考虑改进如何公开它。
    • 为了详细说明,Sage 倾向于将有关绘图的内容放在 show 中(因此包括轴,默认为 axes=True),而绘图本身和/或特定数据点是如果有意义的话,无需实际绘制情节即可访问。
    • 您可以通过访问/修改my_graphics_obj.SHOW_OPTIONS 字典来设置和查看稍后将用于show 命令的设置。
    • 对于坐标轴标签,可能是show(myplot,axes_labels=('$x$','$y$'))
    【解决方案2】:
    • 轴标签:myplot.xlabel("text for x axis")myplot.ylabel("text for y axis")
    • 标题:myplot.title("My super plot")
    • 图例:将label="Fancy plot" 参数添加到plot 的调用中,并使用legend() 创建图例

    请参阅herethere 了解更多说明。

    【讨论】:

    • 不幸的是,这不起作用——出现了一个异常,指出“xlabel”、“ylabel”和“title”不是 Graphics 对象中的成员(这似乎与matplotlib)。
    • 是的,Sage 图形对象不是 matplotlib 对象,尽管当我们保存对象(例如查看)时,我们在那里使用 mpl。例如,这允许我们在不导入 mpl 的情况下创建东西。
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 2015-12-19
    • 2018-10-29
    • 2022-01-21
    • 1970-01-01
    • 2017-01-29
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多