将颜色条添加到Julia PyPlot中的子图

时间:2019-05-15 10:42:04

标签: python matplotlib julia

我已尝试将this answer中的Python代码转换为Julia,如下所示。

using PyPlot
# normal distribution center at x=0 and y=5
x,y = randn(100000), randn(100000) .+ 5
# plot 2d histogram with color bar
fig, ax = plt.subplots()
h = ax.hist2d(x, y, bins=40)
plt.colorbar(h[3], ax=ax)

注释:这里的.+5表示按5逐元素添加向量。在Julia中,可以直接使用plt

但是,我收到一个错误。由于我很少用Python编写程序,因此erorr消息不会使我走到了解决之道。

PyError ($(Expr(:escape, :(ccall(#= /home/vin100/.julia/packages/PyCall/ttONZ/src/pyfncall.jl:44 =# @pysym(:PyObject_Call), PyPtr, (PyPtr, PyPtr, PyPtr), o, pyargsptr, kw))))) <class 'AttributeError'>
AttributeError("'numpy.ndarray' object has no attribute 'autoscale_None'",)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py", line 2100, in colorbar
    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/figure.py", line 2129, in colorbar
    cb = cbar.colorbar_factory(cax, mappable, **cb_kw)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/colorbar.py", line 1566, in colorbar_factory
    cb = Colorbar(cax, mappable, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/colorbar.py", line 1072, in __init__
    mappable.autoscale_None()
in top-level scope at base/none
in  at base/none
in #call#111 at PyCall/ttONZ/src/pyfncall.jl:89 
in _pycall! at PyCall/ttONZ/src/pyfncall.jl:11
in _pycall! at PyCall/ttONZ/src/pyfncall.jl:29
in __pycall! at PyCall/ttONZ/src/pyfncall.jl:44
in macro expansion at PyCall/ttONZ/src/exception.jl:84 
in pyerr_check at PyCall/ttONZ/src/exception.jl:64 
in pyerr_check at PyCall/ttONZ/src/exception.jl:60 

如何在Julia的PyPlot制作的2D直方图中添加颜色条?

1 个答案:

答案 0 :(得分:0)

事实证明,我已经忘记了Python和Julia中的数组索引之间的区别。对于前者和后者,数组分别从索引零和一开始。因此,在上述代码块的索引3中添加一个就足够了

using PyPlot
# normal distribution center at x=0 and y=5
x,y = randn(100000), randn(100000) .+ 5
# plot 2d histogram with color bar
fig, ax = plt.subplots()
h = ax.hist2d(x, y, bins=40)
plt.colorbar(h[4], ax=ax)

为了获得带有颜色条的二维直方图。

Julia Pyplot 2d histogram