2016-11-27 24 views
0

我正在嘗試做一個非常簡單的散點圖,誤差線和半徑標尺。與我發現的教程有點不同的是,散點圖的顏色應該跟蹤不同的數量。一方面,我能夠用數據做錯誤條的散點圖,但只有一種顏色。另一方面,我意識到有正確顏色的散點圖,但沒有錯誤條。 我不能將兩種不同的東西結合在一起。使用假數據python scatter plot with errorbars and colors mapping a physical quantity

下面的例子:

#!/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() 

我甚至試過errorbar後繪製散點圖,但由於某種原因都繪製在同一窗口放在背景對於errorplot。 任何想法?

謝謝!

回答

0

here所述,您可以將顏色設置爲由errorbar返回的LineCollection對象。

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

+0

這就是我一直在尋找! – andrea