我一直在使用下面的代码来绘制运行4个函数所花费的时间。 x轴表示执行次数,而y轴表示花费的时间 运行一个功能。
我想知道你是否可以帮我完成以下任务:
1)设置x轴的限制,以便仅显示正值(x表示 每个函数执行的次数,因此总是正数)
2)为4个功能
创建一个图例谢谢,
标记
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)
答案 0 :(得分:22)
您需要致电legend
以显示图例。 label
kwarg仅在相关艺术家对象上设置_label
属性。它是为了方便起见,因此图例中的标签可以与绘图命令明确关联。如果没有明确调用ax.legend(...)
,它就不会将图例添加到图中。此外,您需要ax.set_xlim
,而不是ax.xlim
来调整x轴限制。也请查看ax.axis
。
听起来你想要这样的东西:
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)