python - 散点图中的轴范围

标签 python matplotlib limit scatter

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

最佳答案

您需要调用legend为了传说的出现。 label kwarg 仅在相关艺术家对象上设置 _label 属性。它的存在是为了方便,以便图例中的标签可以清楚地与绘图命令相关联。如果不显式调用 ax.legend(...),它不会将图例添加到图中。此外,您需要 ax.set_xlim 而不是 ax.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)

enter image description here

关于python - 散点图中的轴范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7376330/

相关文章:

python - Matplotlib basemap drawcounties 不起作用

MySQL 从表中获取前 3 位供应商

mysql - 如何使用Access数据库模拟MySQL的LIMIT子句?

python - python,matplotlib:谱图数据数组值与谱图图不匹配

python - 如何在 Matplotlib 中的同一个图形上绘制多个函数?

python - 值错误 : readline of closed file in Python

python - 在同一图表中绘制 pandas 中的两个数字列,日期在 x 轴上

php - 从 SQL 表中选择行的百分比?

python - Scipy 的 sign() 不能保证有效吗?

python - Pyramid 应用程序的版权符号