简体   繁体   English

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

[英]Add colorbar to subplot in Julia PyPlot

I've tried to translate the Python code in this answer into Julia as follows. 我试着将这个答案中的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)

Remarks: Here, .+5 means adding a vector element-wise by 5 . 备注:这里, .+5表示向量元素加5 In Julia, one can directly use plt . 在朱莉娅,人们可以直接使用plt

However, I received an error. 但是,我收到了一个错误。 Since I rarely write programmes in Python, the erorr message doesn't bring me far to the solution. 由于我很少用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 

How can I add color bar to 2D histogram made by PyPlot in Julia? 如何在Julia中将PyPlot添加到2D直方图中添加颜色条?

It turns out that I've forgotten the difference between the array indexing in Python and in Julia. 事实证明,我已经忘记了Python和Julia中的数组索引之间的区别。 For the former and later, an array starts at indices zero and one respectively. 对于前者和后者,数组分别从索引0和1开始。 Therefore, it suffices to add one into the index 3 in the above code block 因此,在上述代码块中将索引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)

in order to get a 2D histogram with color bar. 为了得到带有彩条的2D直方图。

Julia Pyplot 2d直方图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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