How to add titles, axis label, and legend in sagemath?

Question:

I’m currently making some graphs using the online workbook hosted by sagemath.

This is an example of some code I’m making to try and generate a graph:

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()

It’s very basic — it’s essentially two scatter plots juxtaposed on top of each other.

Is there a way to easily add axis labels, a legend, and optionally a title?

I managed to hack out a solution that lets me add axis labels, but it looks really ugly and stupid.

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')

Is there an easier way to add axis labels, legend, and a title?

Asked By: Michael0x2a

||

Answers:

  • Axis Labels: myplot.xlabel("text for x axis"), myplot.ylabel("text for y axis")
  • Title: myplot.title("My super plot")
  • Legend: Add a label="Fancy plot" argument to the calls of plot and create the legend with legend()

See here and there for further explanations.

Answered By: halex

I eventually found the documentation for sagemath’s Graphics object.

I had to do it like this:

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")

I’m not entirely certain why there’s no title method and why the title has to be specified inside show when the axes don’t have to be, but this does appear to work.

Answered By: Michael0x2a

Here’s an example of combining everything in a straighforward way, first defining the plot attributes then the data.

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)
Answered By: Bret Hess
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.