Home > database >  color specification via iterable
color specification via iterable

Time:09-05

I'm plotting a series of curves using iterables where I specify a color, according to a colormap, for each of the plots.

While the following code does its job:

f, ax = plt.subplots(figsize=(8, 4), constrained_layout=True)

cmap = plt.get_cmap("jet_r")
colors = [
    cmap(float(idx) / len(my_traces_norm)) for idx, _ in enumerate(my_traces_norm)
]


for idx, (c, v) in enumerate(zip(colors, voltages)):
    ax.plot(
        my_data["axes"]["t"],
        my_traces_norm[idx].T,
        color=c,
        alpha=0.7,
        ls="--",
        linewidth=1,
        label=f"{v} V",
    )

Although it works for the labels, if I try to use the iterable for the color, I'm getting this error:

ValueError: [(0.5, 0.0, 0.0, 1.0), (0.9099821746880571, 0.0007262164124910357, 0.0, 1.0), (1.0, 0.33478576615831523, 0.0, 1.0), (1.0, 0.6688453159041395, 0.0, 1.0), (0.9203036053130929, 1.0, 0.047438330170778, 1.0), (0.6293485135989879, 1.0, 0.3383934218848831, 1.0), (0.338393421884883, 1.0, 0.6293485135989881, 1.0), (0.04743833017077803, 0.9588235294117647, 0.9203036053130932, 1.0), (0.0, 0.5823529411764705, 1.0, 1.0), (0.0, 0.22156862745098038, 1.0, 1.0), (0.0, 0.0, 0.9099821746880573, 1.0)] is not a valid value for color

The code is this one:

f, ax = plt.subplots(figsize=(8, 4), constrained_layout=True)

cmap = plt.get_cmap("jet_r")
colors = [
    cmap(float(idx) / len(my_traces_norm)) for idx, _ in enumerate(my_traces_norm)
]    

ax.plot(
    my_data["axes"]["t"],
    my_traces_norm.T,
    color=[c for c in colors],
    alpha=0.7,
    ls="--",
    linewidth=1,
    label=[f"{v} V" for v in voltages],
)

CodePudding user response:

While it is not posible to pass multiple colors using the color parameter, you can set a colorcycle for the Axes using ax.set_prop_cycle():

f, ax = plt.subplots(figsize=(8, 4), constrained_layout=True)

cmap = plt.get_cmap("jet_r")
colors = [
    cmap(float(idx) / len(my_traces_norm)) for idx, _ in enumerate(my_traces_norm)
]
ax.set_prop_cycle(color=colors)

ax.plot(
    my_data["axes"]["t"],
    my_traces_norm.T,
    alpha=0.7,
    ls="--",
    linewidth=1,
    label=[f"{v} V" for v in voltages],
)
  • Related