【问题标题】:Adding y=x to a matplotlib scatter plot if I haven't kept track of all the data points that went in如果我没有跟踪所有进入的数据点,则将 y=x 添加到 matplotlib 散点图
【发布时间】:2014-10-19 06:45:58
【问题描述】:

这是一些使用 matplotlib 对多个不同系列进行散点图的代码,然后添加 y=x 行:

import numpy as np, matplotlib.pyplot as plt, matplotlib.cm as cm, pylab

nseries = 10
colors = cm.rainbow(np.linspace(0, 1, nseries))

all_x = []
all_y = []
for i in range(nseries):
    x = np.random.random(12)+i/10.0
    y = np.random.random(12)+i/5.0
    plt.scatter(x, y, color=colors[i])
    all_x.extend(x)
    all_y.extend(y)

# Could I somehow do the next part (add identity_line) if I haven't been keeping track of all the x and y values I've seen?
identity_line = np.linspace(max(min(all_x), min(all_y)),
                            min(max(all_x), max(all_y)))
plt.plot(identity_line, identity_line, color="black", linestyle="dashed", linewidth=3.0)

plt.show()

为了实现这一点,我必须跟踪散点图中的所有 x 和 y 值,以便知道identity_line 应该从哪里开始和结束。即使我没有绘制所有点的列表,有没有办法让 y=x 显示出来?我认为 matplotlib 中的某些东西可以在事后为我提供所有点的列表,但我无法弄清楚如何获得该列表。

【问题讨论】:

    标签: python matplotlib plot scatter-plot


    【解决方案1】:

    您不需要了解任何有关您的数据的信息本身。您可以摆脱 matplotlib Axes 对象将告诉您的有关数据的内容。

    见下文:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # random data 
    N = 37
    x = np.random.normal(loc=3.5, scale=1.25, size=N)
    y = np.random.normal(loc=3.4, scale=1.5, size=N)
    c = x**2 + y**2
    
    # now sort it just to make it look like it's related
    x.sort()
    y.sort()
    
    fig, ax = plt.subplots()
    ax.scatter(x, y, s=25, c=c, cmap=plt.cm.coolwarm, zorder=10)
    

    这是好的部分:

    lims = [
        np.min([ax.get_xlim(), ax.get_ylim()]),  # min of both axes
        np.max([ax.get_xlim(), ax.get_ylim()]),  # max of both axes
    ]
    
    # now plot both limits against eachother
    ax.plot(lims, lims, 'k-', alpha=0.75, zorder=0)
    ax.set_aspect('equal')
    ax.set_xlim(lims)
    ax.set_ylim(lims)
    fig.savefig('/Users/paul/Desktop/so.png', dpi=300)
    

    等等

    【讨论】:

      【解决方案2】:

      一行:

      ax.plot([0,1],[0,1], transform=ax.transAxes)

      无需修改 xlim 或 ylim。

      【讨论】:

      • 仅在纵横比为 1 时有效
      【解决方案3】:

      如果将 scalex 和 scaley 设置为 False,则可以节省一些记账。这是我最近用来覆盖 y=x 的:

      xpoints = ypoints = plt.xlim()
      plt.plot(xpoints, ypoints, linestyle='--', color='k', lw=3, scalex=False, scaley=False)
      

      或者如果你有一个轴:

      xpoints = ypoints = ax.get_xlim()
      ax.plot(xpoints, ypoints, linestyle='--', color='k', lw=3, scalex=False, scaley=False)
      

      当然,这不会给你一个正方形的纵横比。如果您关心这一点,请使用 Paul H 的解决方案。

      【讨论】:

        猜你喜欢
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多