简体   繁体   中英

Add colorbar to subplot in Julia PyPlot

I've tried to translate the Python code in this answer into Julia as follows.

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)

Remarks: Here, .+5 means adding a vector element-wise by 5 . In Julia, one can directly use plt .

However, I received an error. Since I rarely write programmes in Python, the erorr message doesn't bring me far to the solution.

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 

How can I add color bar to 2D histogram made by PyPlot in Julia?

It turns out that I've forgotten the difference between the array indexing in Python and in Julia. For the former and later, an array starts at indices zero and one respectively. Therefore, it suffices to add one into the index 3 in the above code block

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)

in order to get a 2D histogram with color bar.

Julia Pyplot 2d直方图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM