我想繪製一些數據使用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 ='horizontal'))。在圖像庫中看到你想要的情節是非常令人沮喪的,但是這個例子不起作用。第二套眼睛將不勝感激!
請將代碼量減少到_minimum_所需的_minimum_以重現錯誤並超過_full_堆棧跟蹤。 – tacaswell
和你使用的是什麼版本的matplotlib?我認爲你遇到了一個錯誤。 – tacaswell
下次我會盡量減少代碼。大部分是必要的,僅僅是因爲我想讓人們看到我使用的是哪些邊界和哪些數據。我正在使用matplotlib版本1.2.1。現在包含完整的堆棧跟蹤。另外,我剛剛在我的另一臺計算機上使用默認的matplotlibrc文件和非anaconda打包的分發版本嘗試了這些,因此這兩者似乎都不是原因。 – astromax