Matplotlib:颜色栏不断缩小

时间:2017-07-08 22:43:57

标签: python matplotlib colorbar

我编写了一个代码,其中有一个名为array2的数组,其中的数字介于0.1.之间。当我点击imshow显示的数组时,数组中的单元格取值2.并变为红色。

然后我添加了一个颜色条,但是一旦我点击它就不断缩小,细胞也不会变红。

我做错了什么?

没有色条的代码(工作正常)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from random import random


def test(n):
    array1 = np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            array1[i,j] = random()
    return array1


# Array
global array2
array2 = test(10)


# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)


# Matplotlib
fig, axes = plt.subplots(1)
fig.tight_layout()

plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')


def onclick(event):
    global x, y
    x, y = int(event.xdata), int(event.ydata)
    array2[y,x] = 2.

    plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')


fig.canvas.mpl_connect('button_press_event', onclick)

enter image description here

带有colorbar的代码(不起作用)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from random import random 


def test(n):
    array1 = np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            array1[i,j] = random()
    return array1


# Array
global array2
array2 = test(10)


# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)


# Matplotlib
fig, axes = plt.subplots(1)
fig.tight_layout()

im = plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

divider = make_axes_locatable(axes)
cax = divider.append_axes("right", size="13%", pad=0.2)

cb = plt.colorbar(im, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1])

cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

def onclick(event):
    global x, y
    x, y = int(event.xdata), int(event.ydata)
    array2[y,x] = 2.

    im = plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

    divider = make_axes_locatable(axes)
    cax = divider.append_axes("right", size="13%", pad=0.2)

    cb = plt.colorbar(im, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1])

    cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)  


fig.canvas.mpl_connect('button_press_event', onclick)

enter image description here

1 个答案:

答案 0 :(得分:2)

最好只更新imshow,而不是每次执行点击时都绘制一个新的.set_data()。这可以使用fig方法完成。优点是色条可以保持原样并且不会被触摸。

一般情况下,在进行交互式操作时,最好直接使用绘图对象而不是pyplot。因此,在大多数情况下,使用axplt代替int(np.round(event.xdata))

请注意,要准确捕捉像素上的点击,您需要先围绕坐标import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors from matplotlib import cm from mpl_toolkits.axes_grid1 import make_axes_locatable global array2 array2 = np.random.rand(10,10) # Colormap greens = cm.Greens(np.linspace(0,1, num=50)) greensfill = cm.Greens(np.ones(25)) red = [(1,0,0,1)]*len(greens) gray = [(.5,.5,.5,1)]*len(greens) colors = np.vstack((greens, greensfill, red, gray)) mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors) # Matplotlib fig, ax = plt.subplots() fig.tight_layout() im = ax.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="13%", pad=0.2) cb = fig.colorbar(im, ax =ax, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1]) cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5) def onclick(event): x, y = int(np.round(event.xdata)), int(np.round(event.ydata)) array2[y,x] = 2. im.set_data(array2) fig.canvas.draw_idle() fig.canvas.mpl_connect('button_press_event', onclick) plt.show()

 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
<asp:DataList ID="dtaddedOrderItem" runat="server" OnItemDataBound="dtaddedCartItem_ItemDataBound"  OnItemCommand="dtaddedCartItem_ItemCommand">

<ItemTemplate>
<asp:DataList ID="dtaddedsubserviceitem" runat="server" OnItemDataBound="dtaddedsubserviceitem_ItemDataBound" OnItemCommand="dtaddedsubserviceitem_ItemCommand">
<FooterTemplate>                                                                                                          
<div id="footeraddserviceshide" runat="server">                                                                                                        
<tr>
<td>
<asp:DropDownList ID="ddmainservices" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddmainservices_SelectedIndexChanged"></asp:DropDownList>
<asp:HiddenField ID="hdfooterjeweleryid" runat="server" Value="" />
</td>
<td>
 <asp:DropDownList ID="ddsubservices" runat="server" Visible="false" AutoPostBack="true" OnSelectedIndexChanged="ddsubservices_SelectedIndexChanged"></asp:DropDownList>
 <asp:DropDownList ID="ddsizing" runat="server" Visible="false"></asp:DropDownList>
 </td>
 <td>
<asp:TextBox ID="txtdescription" runat="server" Visible="false"></asp:TextBox>
 <td style="padding: 10px;">
  <asp:LinkButton ID="lnkaddservices" CommandArgument="" runat="server">Add</asp:LinkButton>
 </td>
 </tr>
  </div>
  </FooterTemplate>
 </asp:DataList>
</ItemTemplate>                                                                        
</asp:DataList>
 </ContentTemplate>
</asp:UpdatePanel>