def test_color_with_alpha(self): x = y = [1, 2, 3] m = Path(color=(.4, .9, .2, .5), fillcolor=(.2, .2, .3, .9)) p = Plot(x=x, y=y).add(m).plot() line, = p._figure.axes[0].get_lines() assert same_color(line.get_color(), m.color) assert same_color(line.get_markeredgecolor(), m.color) assert same_color(line.get_markerfacecolor(), m.fillcolor)
def test_shared_colors_direct(self): x = y = [1, 2, 3] m = Path(color="r") p = Plot(x=x, y=y).add(m).plot() line, = p._figure.axes[0].get_lines() assert same_color(line.get_color(), "r") assert same_color(line.get_markeredgecolor(), "r") assert same_color(line.get_markerfacecolor(), "r")
def test_color_and_alpha(self): x = y = [1, 2, 3] m = Path(color=(.4, .9, .2), fillcolor=(.2, .2, .3), alpha=.5) p = Plot(x=x, y=y).add(m).plot() line, = p._figure.axes[0].get_lines() assert same_color(line.get_color(), to_rgba(m.color, m.alpha)) assert same_color(line.get_markeredgecolor(), to_rgba(m.color, m.alpha)) assert same_color(line.get_markerfacecolor(), to_rgba(m.fillcolor, m.alpha))
def test_separate_colors_direct(self): x = y = [1, 2, 3] y = [1, 2, 3] m = Path(color="r", edgecolor="g", fillcolor="b") p = Plot(x=x, y=y).add(m).plot() line, = p._figure.axes[0].get_lines() assert same_color(line.get_color(), m.color) assert same_color(line.get_markeredgecolor(), m.edgecolor) assert same_color(line.get_markerfacecolor(), m.fillcolor)
def test_patch_modification(): fig = plt.figure() ax = fig.add_subplot(projection="3d") circle = Circle((0, 0)) ax.add_patch(circle) art3d.patch_2d_to_3d(circle) circle.set_facecolor((1.0, 0.0, 0.0, 1)) assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1)) fig.canvas.draw() assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1))
def test_shared_colors_mapped(self): x = y = [1, 2, 3, 4] c = ["a", "a", "b", "b"] m = Path() p = Plot(x=x, y=y, color=c).add(m).plot() ax = p._figure.axes[0] for i, line in enumerate(ax.get_lines()): assert same_color(line.get_color(), f"C{i}") assert same_color(line.get_markeredgecolor(), f"C{i}") assert same_color(line.get_markerfacecolor(), f"C{i}")
def test_LineCollection_args(): with pytest.warns(MatplotlibDeprecationWarning): lc = LineCollection(None, 2.2, 'r', zorder=3, facecolors=[0, 1, 0, 1]) assert lc.get_linewidth()[0] == 2.2 assert mcolors.same_color(lc.get_edgecolor(), 'r') assert lc.get_zorder() == 3 assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]]) # To avoid breaking mplot3d, LineCollection internally sets the facecolor # kwarg if it has not been specified. Hence we need the following test # for LineCollection._set_default(). lc = LineCollection(None, facecolor=None) assert mcolors.same_color(lc.get_facecolor(), 'none')
def test_same_color(): assert mcolors.same_color('k', (0, 0, 0)) assert not mcolors.same_color('w', (1, 1, 0)) assert mcolors.same_color(['red', 'blue'], ['r', 'b']) assert mcolors.same_color('none', 'none') assert not mcolors.same_color('none', 'red') with pytest.raises(ValueError): mcolors.same_color(['r', 'g', 'b'], ['r']) with pytest.raises(ValueError): mcolors.same_color(['red', 'green'], 'none')
def test_invert_color(): cmap1 = cm.import_colormap('jet') cmap2 = cm.invert_colormap(cmap1) c1 = np.array(cmap1(0)) c1[:3] = 1 - c1[:3] c2 = np.array(cmap2(0)) assert col.same_color(c1, c2)
def test_color_with_alpha(self): x = y = [1, 2, 3] m = Paths(color=(.2, .6, .9, .5)) p = Plot(x=x, y=y).add(m).plot() lines, = p._figure.axes[0].collections assert same_color(lines.get_colors().squeeze(), m.color)
def test_color_and_alpha(self): x = y = [1, 2, 3] m = Paths(color=(.2, .6, .9), alpha=.5) p = Plot(x=x, y=y).add(m).plot() lines, = p._figure.axes[0].collections assert same_color(lines.get_colors().squeeze(), to_rgba(m.color, m.alpha))
def test_rectangle_handles(): ax = get_ax() def onselect(epress, erelease): pass tool = widgets.RectangleSelector(ax, onselect=onselect, maxdist=10, interactive=True, marker_props={ 'markerfacecolor': 'r', 'markeredgecolor': 'b' }) tool.extents = (100, 150, 100, 150) assert tool.corners == ((100, 150, 150, 100), (100, 100, 150, 150)) assert tool.extents == (100, 150, 100, 150) assert tool.edge_centers == ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150)) assert tool.extents == (100, 150, 100, 150) # grab a corner and move it do_event(tool, 'press', xdata=100, ydata=100) do_event(tool, 'onmove', xdata=120, ydata=120) do_event(tool, 'release', xdata=120, ydata=120) assert tool.extents == (120, 150, 120, 150) # grab the center and move it do_event(tool, 'press', xdata=132, ydata=132) do_event(tool, 'onmove', xdata=120, ydata=120) do_event(tool, 'release', xdata=120, ydata=120) assert tool.extents == (108, 138, 108, 138) # create a new rectangle do_event(tool, 'press', xdata=10, ydata=10) do_event(tool, 'onmove', xdata=100, ydata=100) do_event(tool, 'release', xdata=100, ydata=100) assert tool.extents == (10, 100, 10, 100) # Check that marker_props worked. assert mcolors.same_color( tool._corner_handles.artist.get_markerfacecolor(), 'r') assert mcolors.same_color( tool._corner_handles.artist.get_markeredgecolor(), 'b')
def _motion(self, event): if self.ignore(event): return c = self.hovercolor if event.inaxes == self.ax else self.color if not colors.same_color(c, self.ax.get_facecolor()): self.ax.set_facecolor(c) if self.drawon: self.ax.draw_artist(self.ax) self.ax.figure.canvas.blit(self.ax.bbox)
def test_props_direct(self): x = y = [1, 2, 3] m = Paths(color="r", linewidth=1, linestyle=(3, 1)) p = Plot(x=x, y=y).add(m).plot() lines, = p._figure.axes[0].collections assert same_color(lines.get_color().squeeze(), m.color) assert lines.get_linewidth().item() == m.linewidth assert lines.get_linestyle()[0] == (0, list(m.linestyle))
def test_contour_legend_elements(): from matplotlib.collections import LineCollection x = np.arange(1, 10) y = x.reshape(-1, 1) h = x * y colors = ['blue', '#00FF00', 'red'] cs = plt.contour(h, levels=[10, 30, 50], colors=colors, extend='both') artists, labels = cs.legend_elements() assert labels == ['$x = 10.0$', '$x = 30.0$', '$x = 50.0$'] assert all(isinstance(a, LineCollection) for a in artists) assert all(same_color(a.get_color(), c) for a, c in zip(artists, colors))
def test_direct_properties(self): x = [1, 2] ymin = [1, 4] ymax = [2, 3] m = Interval(color="r", linewidth=4) p = Plot(x=x, ymin=ymin, ymax=ymax).add(m).plot() lines, = p._figure.axes[0].collections for i, path in enumerate(lines.get_paths()): assert same_color(lines.get_colors()[i], m.color) assert lines.get_linewidths()[i] == m.linewidth
def test_rectangle_handles(): ax = get_ax() def onselect(epress, erelease): pass tool = widgets.RectangleSelector(ax, onselect=onselect, grab_range=10, interactive=True, handle_props={'markerfacecolor': 'r', 'markeredgecolor': 'b'}) tool.extents = (100, 150, 100, 150) assert_allclose(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150))) assert tool.extents == (100, 150, 100, 150) assert_allclose(tool.edge_centers, ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))) assert tool.extents == (100, 150, 100, 150) # grab a corner and move it click_and_drag(tool, start=(100, 100), end=(120, 120)) assert tool.extents == (120, 150, 120, 150) # grab the center and move it click_and_drag(tool, start=(132, 132), end=(120, 120)) assert tool.extents == (108, 138, 108, 138) # create a new rectangle click_and_drag(tool, start=(10, 10), end=(100, 100)) assert tool.extents == (10, 100, 10, 100) # Check that marker_props worked. assert mcolors.same_color( tool._corner_handles.artists[0].get_markerfacecolor(), 'r') assert mcolors.same_color( tool._corner_handles.artists[0].get_markeredgecolor(), 'b')
def test_mapped_color(self): x = [1, 2, 1, 2] ymin = [1, 4, 3, 2] ymax = [2, 3, 1, 4] group = ["a", "a", "b", "b"] p = Plot(x=x, ymin=ymin, ymax=ymax, color=group).add(Interval()).plot() lines, = p._figure.axes[0].collections for i, path in enumerate(lines.get_paths()): verts = path.vertices.T assert_array_equal(verts[0], [x[i], x[i]]) assert_array_equal(verts[1], [ymin[i], ymax[i]]) assert same_color(lines.get_colors()[i], f"C{i // 2}")
def test_contourf_legend_elements(): from matplotlib.patches import Rectangle x = np.arange(1, 10) y = x.reshape(-1, 1) h = x * y cs = plt.contourf(h, levels=[10, 30, 50], colors=['#FFFF00', '#FF00FF', '#00FFFF'], extend='both') cs.cmap.set_over('red') cs.cmap.set_under('blue') cs.changed() artists, labels = cs.legend_elements() assert labels == [ '$x \\leq -1e+250s$', '$10.0 < x \\leq 30.0$', '$30.0 < x \\leq 50.0$', '$x > 1e+250s$' ] expected_colors = ('blue', '#FFFF00', '#FF00FF', 'red') assert all(isinstance(a, Rectangle) for a in artists) assert all( same_color(a.get_facecolor(), c) for a, c in zip(artists, expected_colors))
def get_color(self, target, ispin, spin_proj): # Choose project color color=list(mcolors.TABLEAU_COLORS.keys()) if ispin==2 or ispin==4 and spin_proj != None: color.remove('tab:blue') color.remove('tab:red') if len(target) > len(color): newcolor = list(mcolors.CSS4_COLORS.keys()) for i in range(len(color), len(target)): num = random.randint(0, len(newcolor)-1) color.append(newcolor.pop(num)) for t in target: if len(t) == 3: for i,c in enumerate(color): if mcolors.same_color(t[2],c): del color[i] for i, t in enumerate(target): if len(t) == 3: color.insert(i,t[2]) return color
def test_add_black_to_mid(): cmap = cm.add_black('jet', loc='mid') assert col.same_color(cmap(cmap.N//2 - 1), 'k')
def test_color_logic(pcfunc): z = np.arange(12).reshape(3, 4) # Explicitly set an edgecolor. pc = pcfunc(z, edgecolors='red', facecolors='none') pc.update_scalarmappable() # This is called in draw(). # Define 2 reference "colors" here for multiple use. face_default = mcolors.to_rgba_array(pc._get_default_facecolor()) mapped = pc.get_cmap()(pc.norm((z.ravel()))) # Github issue #1302: assert mcolors.same_color(pc.get_edgecolor(), 'red') # Check setting attributes after initialization: pc = pcfunc(z) pc.set_facecolor('none') pc.set_edgecolor('red') pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), 'none') assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) pc.set_alpha(0.5) pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]]) pc.set_alpha(None) # restore default alpha pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Reset edgecolor to default. pc.set_edgecolor(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), mapped) pc.set_facecolor(None) # restore default for facecolor pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), 'none') # Turn off colormapping entirely: pc.set_array(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_edgecolor(), 'none') assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped # Turn it back on by restoring the array (must be 1D!): pc.set_array(z.ravel()) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), 'none') # Give color via tuple rather than string. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0)) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Provide an RGB array; mapping overrides it. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3))) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Turn off the mapping. pc.set_array(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3))) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # And an RGBA array. pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4))) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), mapped) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) # Turn off the mapping. pc.set_array(None) pc.update_scalarmappable() assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4))) assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
def test_same_color(): assert mcolors.same_color('k', (0, 0, 0)) assert not mcolors.same_color('w', (1, 1, 0))
def test_same_color(): assert mcolors.same_color('k', (0, 0, 0)) assert not mcolors.same_color('w', (1, 1, 0))
def test_add_black_to_start(): cmap = cm.add_black('jet') assert col.same_color(cmap(0), 'k')
def test_add_black_to_end(): cmap = cm.add_black('jet', loc='end') assert col.same_color(cmap(cmap.N-1), 'k')
def test_BoundaryNorm(): """ GitHub issue #1258: interpolation was failing with numpy 1.7 pre-release. """ boundaries = [0, 1.1, 2.2] vals = [-1, 0, 1, 2, 2.2, 4] # Without interpolation expected = [-1, 0, 0, 1, 2, 2] ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # ncolors != len(boundaries) - 1 triggers interpolation expected = [-1, 0, 0, 2, 3, 3] ncolors = len(boundaries) bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # with a single region and interpolation expected = [-1, 1, 1, 1, 3, 3] bn = mcolors.BoundaryNorm([0, 2.2], ncolors) assert_array_equal(bn(vals), expected) # more boundaries for a third color boundaries = [0, 1, 2, 3] vals = [-1, 0.1, 1.1, 2.2, 4] ncolors = 5 expected = [-1, 0, 2, 4, 5] bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # a scalar as input should not trigger an error and should return a scalar boundaries = [0, 1, 2] vals = [-1, 0.1, 1.1, 2.2] bn = mcolors.BoundaryNorm(boundaries, 2) expected = [-1, 0, 1, 2] for v, ex in zip(vals, expected): ret = bn(v) assert isinstance(ret, int) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) # same with interp bn = mcolors.BoundaryNorm(boundaries, 3) expected = [-1, 0, 2, 3] for v, ex in zip(vals, expected): ret = bn(v) assert isinstance(ret, int) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) # Clipping bn = mcolors.BoundaryNorm(boundaries, 3, clip=True) expected = [0, 0, 2, 2] for v, ex in zip(vals, expected): ret = bn(v) assert isinstance(ret, int) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) # Masked arrays boundaries = [0, 1.1, 2.2] vals = np.ma.masked_invalid([-1., np.NaN, 0, 1.4, 9]) # Without interpolation ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) expected = np.ma.masked_array([-1, -99, 0, 1, 2], mask=[0, 1, 0, 0, 0]) assert_array_equal(bn(vals), expected) # With interpolation bn = mcolors.BoundaryNorm(boundaries, len(boundaries)) expected = np.ma.masked_array([-1, -99, 0, 2, 3], mask=[0, 1, 0, 0, 0]) assert_array_equal(bn(vals), expected) # Non-trivial masked arrays vals = np.ma.masked_invalid([np.Inf, np.NaN]) assert np.all(bn(vals).mask) vals = np.ma.masked_invalid([np.Inf]) assert np.all(bn(vals).mask) # Incompatible extend and clip with pytest.raises(ValueError, match="not compatible"): mcolors.BoundaryNorm(np.arange(4), 5, extend='both', clip=True) # Too small ncolors argument with pytest.raises(ValueError, match="ncolors must equal or exceed"): mcolors.BoundaryNorm(np.arange(4), 2) with pytest.raises(ValueError, match="ncolors must equal or exceed"): mcolors.BoundaryNorm(np.arange(4), 3, extend='min') with pytest.raises(ValueError, match="ncolors must equal or exceed"): mcolors.BoundaryNorm(np.arange(4), 4, extend='both') # Testing extend keyword, with interpolation (large cmap) bounds = [1, 2, 3] cmap = cm.get_cmap('viridis') mynorm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both') refnorm = mcolors.BoundaryNorm([0] + bounds + [4], cmap.N) x = np.random.randn(100) * 10 + 2 ref = refnorm(x) ref[ref == 0] = -1 ref[ref == cmap.N - 1] = cmap.N assert_array_equal(mynorm(x), ref) # Without interpolation cmref = mcolors.ListedColormap(['blue', 'red']) cmref.set_over('black') cmref.set_under('white') cmshould = mcolors.ListedColormap(['white', 'blue', 'red', 'black']) assert mcolors.same_color(cmref.get_over(), 'black') assert mcolors.same_color(cmref.get_under(), 'white') refnorm = mcolors.BoundaryNorm(bounds, cmref.N) mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='both') assert mynorm.vmin == refnorm.vmin assert mynorm.vmax == refnorm.vmax assert mynorm(bounds[0] - 0.1) == -1 # under assert mynorm(bounds[0] + 0.1) == 1 # first bin -> second color assert mynorm(bounds[-1] - 0.1) == cmshould.N - 2 # next-to-last color assert mynorm(bounds[-1] + 0.1) == cmshould.N # over x = [-1, 1.2, 2.3, 9.6] assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2, 3])) x = np.random.randn(100) * 10 + 2 assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x))) # Just min cmref = mcolors.ListedColormap(['blue', 'red']) cmref.set_under('white') cmshould = mcolors.ListedColormap(['white', 'blue', 'red']) assert mcolors.same_color(cmref.get_under(), 'white') assert cmref.N == 2 assert cmshould.N == 3 refnorm = mcolors.BoundaryNorm(bounds, cmref.N) mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='min') assert mynorm.vmin == refnorm.vmin assert mynorm.vmax == refnorm.vmax x = [-1, 1.2, 2.3] assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2])) x = np.random.randn(100) * 10 + 2 assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x))) # Just max cmref = mcolors.ListedColormap(['blue', 'red']) cmref.set_over('black') cmshould = mcolors.ListedColormap(['blue', 'red', 'black']) assert mcolors.same_color(cmref.get_over(), 'black') assert cmref.N == 2 assert cmshould.N == 3 refnorm = mcolors.BoundaryNorm(bounds, cmref.N) mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='max') assert mynorm.vmin == refnorm.vmin assert mynorm.vmax == refnorm.vmax x = [1.2, 2.3, 4] assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2])) x = np.random.randn(100) * 10 + 2 assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))
def test_hex_shorthand_notation(): assert mcolors.same_color("#123", "#112233") assert mcolors.same_color("#123a", "#112233aa")
def test_add_black_fraction(): cmap = cm.add_black('jet', loc=0.25) assert col.same_color(cmap(cmap.N//4 - 1), 'k')
def test_add_white_to_start(): cmap = cm.add_white('jet') assert col.same_color(cmap(0), 'w')
def test_wiridis_start(): cmap = cm.wiridis assert col.same_color(cmap(0), 'w')