I have been using the code below to plot the time spent to run 4 functions. The x axis represents the number of executions whereas the y axis represents the time spent running a function.
I was wondering if you could help me accomplish the following:
1) set the limits of the x axis so that only positive values are shown (x represents the number of times each function was executed and is, therefore, always positive)
2) create a legend for the 4 functions
Thank you,
Mark
import matplotlib
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
开发者_如何学编程
r = mlab.csv2rec('performance.csv')
fig = Figure(figsize=(9,6))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.set_title("Function performance",fontsize=14)
ax.set_xlabel("code executions",fontsize=12)
ax.set_ylabel("time(s)",fontsize=12)
ax.grid(True,linestyle='-',color='0.75')
ax.scatter(r.run,r.function1,s=10,color='tomato');
ax.scatter(r.run,r.function2,s=10,color='violet');
ax.scatter(r.run,r.function3,s=10,color='blue');
ax.scatter(r.run,r.function4,s=10,color='green');
canvas.print_figure('performance.png',dpi=700)
You need to call legend
for the legend to appear. The label
kwarg only sets the _label
attribute on the artist object in question. It's there for convenience, so that the label in the legend can be clearly associated with the plotting command. It won't add the legend to the plot without explicitly calling ax.legend(...)
. Also, you want ax.set_xlim
, not ax.xlim
to adjust the xaxis limits. Have a look at ax.axis
as well.
It sounds like you want something like this:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x = np.arange(0, 22, 2)
f1, f2, f3, f4 = np.cumsum(np.random.random((4, x.size)) - 0.5, axis=1)
# It's much more convenient to just use pyplot's factory functions...
fig, ax = plt.subplots()
ax.set_title("Function performance",fontsize=14)
ax.set_xlabel("code executions",fontsize=12)
ax.set_ylabel("time(s)",fontsize=12)
ax.grid(True,linestyle='-',color='0.75')
colors = ['tomato', 'violet', 'blue', 'green']
labels = ['Thing One', 'Thing Two', 'Thing Three', 'Thing Four']
for func, color, label in zip([f1, f2, f3, f4], colors, labels):
ax.plot(x, func, 'o', color=color, markersize=10, label=label)
ax.legend(numpoints=1, loc='upper left')
ax.set_xlim([0, x.max() + 1])
fig.savefig('performance.png', dpi=100)
精彩评论