python散点图,错误栏和颜色映射物理量

时间:2016-11-27 16:11:07

标签: python matplotlib

我试图用错误条和半月表来做一个非常简单的散点图。与我发现的教程有点不同的是,散点图的颜色应该跟踪不同的数量。一方面,我能够使用带有数据的错误栏进行散点图,但只能使用一种颜色。另一方面,我实现了一个具有正确颜色的散点图,但没有错误栏。 我无法将两种不同的东西结合起来。

这是一个使用虚假数据的例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

n=100
Lx_gas = 1e40*np.random.random(n) + 1e37
Tx_gas = np.random.random(n) + 0.5
Lx_plus_error = Lx_gas
Tx_plus_error = Tx_gas/2.
Tx_minus_error = Tx_gas/4.

#actually positive numbers, this is the quantity that should be traced by the
#color, in this example I use random numbers
Lambda = np.random.random(n) 

#this is actually different from zero, but I want to be sure that this simple
#code works with the log axis
Lx_minus_error = np.zeros_like(Lx_gas)

#normalize the color, to be between 0 and 1
colors = np.asarray(Lambda)
colors -= colors.min()
colors *=  (1./colors.max())

#build the error arrays
Lx_error = [Lx_minus_error, Lx_plus_error]
Tx_error = [Tx_minus_error, Tx_plus_error]

##--------------
##important part of the script

##this works, but all the dots are of the same color
#plt.errorbar(Tx_gas, Lx_gas, xerr = Tx_error,yerr = Lx_error,fmt='o')

##this is what is should be in terms of colors, but it is without the error bars
#plt.scatter(Tx_gas, Lx_gas, marker='s', c=colors)


##what I tried (and failed)
plt.errorbar(Tx_gas, Lx_gas, xerr = Tx_error,yerr = Lx_error,\
        color=colors,  fmt='o')


ax = plt.gca()
ax.set_yscale('log')
plt.show()

我甚至试图在错误栏之后绘制散点图,但出于某种原因,在同一窗口上绘制的所有内容都放在相对于errorplot的背景中。 有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将颜色设置为LineCollection所返回的errorbar对象,如here所述。

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

n=100
Lx_gas = 1e40*np.random.random(n) + 1e37
Tx_gas = np.random.random(n) + 0.5
Lx_plus_error = Lx_gas
Tx_plus_error = Tx_gas/2.
Tx_minus_error = Tx_gas/4.

#actually positive numbers, this is the quantity that should be traced by the
#color, in this example I use random numbers
Lambda = np.random.random(n) 

#this is actually different from zero, but I want to be sure that this simple
#code works with the log axis
Lx_minus_error = np.zeros_like(Lx_gas)

#normalize the color, to be between 0 and 1
colors = np.asarray(Lambda)
colors -= colors.min()
colors *=  (1./colors.max())

#build the error arrays
Lx_error = [Lx_minus_error, Lx_plus_error]
Tx_error = [Tx_minus_error, Tx_plus_error]


sct = plt.scatter(Tx_gas, Lx_gas, marker='s', c=colors)
cb = plt.colorbar(sct)

_, __ ,errorlinecollection = plt.errorbar(Tx_gas, Lx_gas, xerr = Tx_error,yerr = Lx_error, marker='',ls='',zorder=0)
error_color = cb.to_rgba(colors)

errorlinecollection[0].set_color(error_color)
errorlinecollection[1].set_color(error_color)

ax = plt.gca()
ax.set_yscale('log')
plt.show()

enter image description here