2013-08-26 156 views
2

我想绘制一些数据使用Matplotlib的二维散点图函数,同时在x和y轴上生成投影直方图。我发现的例子来自matplotlib图片库(pylab_examples example code: scatter_hist.py)。Matplotlib散点图和直方图

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.ticker import NullFormatter 

# the random data 
x = np.random.randn(1000) 
y = np.random.randn(1000) 

nullfmt = NullFormatter()   # no labels 

# definitions for the axes 
left, width = 0.1, 0.65 
bottom, height = 0.1, 0.65 
bottom_h = left_h = left+width+0.02 

rect_scatter = [left, bottom, width, height] 
rect_histx = [left, bottom_h, width, 0.2] 
rect_histy = [left_h, bottom, 0.2, height] 

# start with a rectangular Figure 
plt.figure(1, figsize=(8,8)) 

axScatter = plt.axes(rect_scatter) 
axHistx = plt.axes(rect_histx) 
axHisty = plt.axes(rect_histy) 

# no labels 
axHistx.xaxis.set_major_formatter(nullfmt) 
axHisty.yaxis.set_major_formatter(nullfmt) 

# the scatter plot: 
axScatter.scatter(x, y) 

# now determine nice limits by hand: 
binwidth = 0.25 
xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))]) 
lim = (int(xymax/binwidth) + 1) * binwidth 

axScatter.set_xlim((-lim, lim)) 
axScatter.set_ylim((-lim, lim)) 

bins = np.arange(-lim, lim + binwidth, binwidth) 

axHistx.hist(x, bins=bins) 
axHisty.hist(y, bins=bins, orientation='horizontal') 

axHistx.set_xlim(axScatter.get_xlim()) 
axHisty.set_ylim(axScatter.get_ylim()) 

plt.show() 

唯一的问题是该示例不起作用。我收到以下错误:

~$ python ~/Desktop/scatter_and_hist.py 
Traceback (most recent call last): 
    File "/Users/username/Desktop/scatter_and_hist.py", line 45, in <module> 
    axHisty.hist(y, bins=bins, orientation='horizontal') 
    File "//anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 8180, in hist 
    color=c, bottom=bottom) 
TypeError: barh() got multiple values for keyword argument 'bottom' 

我已经通过代码并隔离了问题。它是导致问题的第45行(axHisty.hist(y,bin = bin,orientation ='horizo​​ntal'))。在图像库中看到你想要的情节是非常令人沮丧的,但是这个例子不起作用。第二套眼睛将不胜感激!

+1

请将代码量减少到_minimum_所需的_minimum_以重现错误并超过_full_堆栈跟踪。 – tacaswell

+1

和你使用的是什么版本的matplotlib?我认为你遇到了一个错误。 – tacaswell

+0

下次我会尽量减少代码。大部分是必要的,仅仅是因为我想让人们看到我使用的是哪些边界和哪些数据。我正在使用matplotlib版本1.2.1。现在包含完整的堆栈跟踪。另外,我刚刚在我的另一台计算机上使用默认的matplotlibrc文件和非anaconda打包的分发版本尝试了这些,因此这两者似乎都不是原因。 – astromax

回答

5

您在v1.2.1(https://github.com/matplotlib/matplotlib/pull/1985)中遇到了错误。您可以升级您的matplotlib,使用错误修复功能为您的版本打补丁,或者使用np.histogram并使用您自己的正确参数顺序呼叫barh

作为一个侧面说明,有必要对这个问题的唯一代码:您发布

x = np.random.rand(100) 
plt.hist(x, orientation='horizontal') 
plt.show() 

一切噪音。

+0

是的,但那只是因为你知道方位='横向'是罪魁祸首。如果我知道这是原因,我只会发布相关的代码片段。然而,由我这个用户造成的可能性远远高于它实际上是一个错误 - 因此我试图全面提出我的问题。不过,谢谢你的指针。我会给你一个建议。 – astromax

+1

@astromax对不起,我最近有几天压力很大,而且真的很胡思乱想。 – tacaswell

+1

别担心 - 我没有亲自采取。我试图在更多信息而不是更少的方面犯错,但我确实认为不得不摒弃不必要的代码行可能与没有足够的工作一样糟糕。 – astromax