【问题标题】:Draw horizontal lines from x=0 to data points in matplotlib scatterplot (horizontal stem plot)从 x=0 绘制水平线到 matplotlib 散点图中的数据点(水平茎图)
【发布时间】:2013-02-04 03:20:00
【问题描述】:

考虑以下情节:

由这个函数产生:

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

【问题讨论】:

  • 要从 x=0 到点绘制一条“线”,您应该简单地尝试制作一个条形图,而不是或叠加在现有的条形图上。
  • 您有一个对数图,即无法显示点 x=0。
  • 您可以使用 ax.vlines() 或 ax.axvline(),但实际上它们不会在日志中的 x=0 处显示。
  • @DavidZwicker 感谢您指出这一点。我需要修改我的绘图以便显示 0。
  • @RutgerKassies:好点。还有更直接的pyplot.vlines()pyplot.hlines(),应用于当前坐标区。

标签: python matplotlib plot ipython-notebook


【解决方案1】:

正如 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()documentation 在 Matplotlib 网站上。

【讨论】:

    【解决方案2】:

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

    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()], '--')
    

    结果如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多