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

时间:2013-02-19 12:31:54

标签: python matplotlib plot ipython-notebook

考虑以下情节:

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完成吗?需要添加什么代码?

2 个答案:

答案 0 :(得分:2)

正如Rutger Kassies指出的那样,实际上有一些“干”功能可以从我的其他答案中自动化“手动”方法。水平茎线的函数是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

hlines()的{​​{3}}位于Matplotlib网站上。

Plot with horizontal stem bars

答案 1 :(得分:1)

(请参阅我的其他答案,以获得更快的解决方案。)

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

通过重复的plot()调用(每个词干一个),可以很容易地绘制水平主干。这是一个例子

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轴的左边无限远。