8

我一直在使用下面的代码来绘制运行 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)
4

1 回答 1

25

您需要调用legend以显示图例。kwarglabel仅设置相关_label艺术家对象的属性。它的存在是为了方便,以便图例中的标签可以清楚地与绘图命令相关联。它不会在没有明确调用的情况下将图例添加到情节中ax.legend(...)。此外,您ax.set_xlimax.xlim希望调整 xaxis 限制。也来看看吧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)

在此处输入图像描述

于 2011-09-11T17:02:54.643 回答