在matplotlib散点图(水平杆图)中从x=0到数据点绘制水平线

2024-03-28 11:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下情节:

enter image description here

由此函数生成:

def timeDiffPlot(dataA, dataB, saveto=None, leg=None):
    labels = list(dataA["graph"])
    figure(figsize=screenMedium)
    ax = gca()
    ax.grid(True)
    xi = range(len(labels))
    rtsA = dataA["running"] / 1000.0 # running time in seconds
    rtsB = dataB["running"] / 1000.0 # running time in seconds
    rtsDiff = rtsB - rtsA
    ax.scatter(rtsDiff, xi, color='r', marker='^')
    ax.scatter
    ax.set_yticks(range(len(labels)))
    ax.set_yticklabels(labels)
    ax.set_xscale('log')
    plt.xlim(timeLimits)
    if leg:
        legend(leg)
    plt.draw()
    if saveto:
        plt.savefig(saveto, transparent=True, bbox_inches="tight")

这里重要的是x = 0值的正负差异。最好能更清楚地看到这一点,例如

  • 强调x=0轴
  • 从x=0到绘图标记绘制一条线

这可以用matplotlib完成吗?需要添加什么代码?


Tags: nonetruelabelslenrangepltaxrunning
2条回答

正如Rutger-Kassies所指出的,实际上有一些“stem”函数可以从我的另一个答案中自动实现“手动”方法。水平阀杆的功能是hlines()vlines()用于垂直阀杆):

import numpy
from matplotlib import pyplot

x_arr = numpy.random.random(10)-0.5; y_arr = numpy.arange(10)

pyplot.hlines(y_arr, 0, x_arr, color='red')  # Stems
pyplot.plot(x_arr, y_arr, 'D')  # Stem ends
pyplot.plot([0, 0], [y_arr.min(), y_arr.max()], '--')  # Middle bar

Matplotlib网站上有hlines()documentation

Plot with horizontal stem bars

(请参阅我的另一个答案,以获得更快的解决方案。)

Matplotlib提供垂直的“stem”条:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.stem。但是,我找不到stem()的水平等价物。

尽管如此,通过多次调用(每个调用一个),仍然可以很容易地绘制水平杆。下面是一个例子

import numpy
from matplotlib.pyplot import plot

x_arr = numpy.random.random(10)-0.5; y_arr = numpy.arange(10)

# Stems:
for (x, y) in zip(x_arr, y_arr):
    plot([0, x], [y, y], color='red')
# Stem ends:
plot(x_arr, y_arr, 'D')
# Middle bar:
plot([0, 0], [y_arr.min(), y_arr.max()], '--')

结果如下:

Plot with horizontal stem bars

但是,请注意,当x在对数刻度上时,从x=0绘制条线是没有意义的,正如David Zwicker指出的,因为x=0在x轴的左侧是无限远的。

相关问题 更多 >