Skip to content

Commit 8676c27

Browse files
authored
Merge pull request matplotlib#18423 from danuo/2d_array_color_support
2-D array RGB and RGBA values not understood in plt.plot()
2 parents 5584ba7 + fa2accc commit 8676c27

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

lib/matplotlib/colors.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,10 @@ def _to_rgba_no_colorcycle(c, alpha=None):
265265
f"Value must be within 0-1 range")
266266
return c, c, c, alpha if alpha is not None else 1.
267267
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
268+
# turn 2-D array into 1-D array
269+
if isinstance(c, np.ndarray):
270+
if c.ndim == 2 and c.shape[0] == 1:
271+
c = c.reshape(-1)
268272
# tuple color.
269273
if not np.iterable(c):
270274
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")

lib/matplotlib/tests/test_axes.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6590,3 +6590,22 @@ def test_sharing_does_not_link_positions():
65906590
init_pos = ax1.get_position()
65916591
fig.subplots_adjust(left=0)
65926592
assert (ax1.get_position().get_points() == init_pos.get_points()).all()
6593+
6594+
6595+
@check_figures_equal(extensions=["pdf"])
6596+
def test_2dcolor_plot(fig_test, fig_ref):
6597+
color = np.array([0.1, 0.2, 0.3])
6598+
# plot with 1D-color:
6599+
axs = fig_test.subplots(5)
6600+
axs[0].plot([1, 2], [1, 2], c=color.reshape(-1))
6601+
axs[1].scatter([1, 2], [1, 2], c=color.reshape(-1))
6602+
axs[2].step([1, 2], [1, 2], c=color.reshape(-1))
6603+
axs[3].hist(np.arange(10), color=color.reshape(-1))
6604+
axs[4].bar(np.arange(10), np.arange(10), color=color.reshape(-1))
6605+
# plot with 2D-color:
6606+
axs = fig_ref.subplots(5)
6607+
axs[0].plot([1, 2], [1, 2], c=color.reshape((1, -1)))
6608+
axs[1].scatter([1, 2], [1, 2], c=color.reshape((1, -1)))
6609+
axs[2].step([1, 2], [1, 2], c=color.reshape((1, -1)))
6610+
axs[3].hist(np.arange(10), color=color.reshape((1, -1)))
6611+
axs[4].bar(np.arange(10), np.arange(10), color=color.reshape((1, -1)))

lib/matplotlib/tests/test_colors.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1211,3 +1211,10 @@ def test_colormap_bad_data_with_alpha():
12111211
assert_array_equal(c[0, 0], (0, 0, 0, 0))
12121212
c = cmap([[np.nan, 0.5], [0, 0]], alpha=np.full((2, 2), 0.5))
12131213
assert_array_equal(c[0, 0], (0, 0, 0, 0))
1214+
1215+
1216+
def test_2d_to_rgba():
1217+
color = np.array([0.1, 0.2, 0.3])
1218+
rgba_1d = mcolors.to_rgba(color.reshape(-1))
1219+
rgba_2d = mcolors.to_rgba(color.reshape((1, -1)))
1220+
assert rgba_1d == rgba_2d

0 commit comments

Comments
 (0)