如果我没有跟踪输入的所有数据点,则将y = x添加到matplotlib散点图 [英] Adding y=x to a matplotlib scatter plot if I haven't kept track of all the data points that went in

查看:116
本文介绍了如果我没有跟踪输入的所有数据点,则将y = x添加到matplotlib散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's some code that does scatter plot of a number of different series using matplotlib and then adds the line 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中的某些内容可以为我提供事后所有要点的列表,但是我一直无法弄清楚如何获得该列表.

In order to achieve this I've had to keep track of all the x and y values that went into the scatter plot so that I know where identity_line should start and end. Is there a way I can get y=x to show up even if I don't have a list of all the points that I plotted? I would think that something in matplotlib can give me a list of all the points after the fact, but I haven't been able to figure out how to get that list.

推荐答案

您无需了解有关数据的任何信息本身.您可以摆脱matplotlib Axes对象将告诉您有关数据的事情.

You don't need to know anything about your data per se. You can get away with what your matplotlib Axes object will tell you about the data.

参见下文:

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)

Etvoilà

这篇关于如果我没有跟踪输入的所有数据点,则将y = x添加到matplotlib散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆