简体   繁体   中英

Is it possible to change the color of one individual line in matplotlib's vlines?

From the matplotlib documentation I know I can use a set of colors in the colors argument of vlines like colors=['green', 'yellow', 'red'] etc, but then the colors simply rotate ie: the first line will be green, the second yellow, the third red, 4th green, 5th yellow and so on.

Is there a way to access one line individually and change its color?

You can plot that particular line separately:

ax.vlines([1,2,4,5], 0, 1, colors='red')
ax.vlines(3, 0, 1, colors='blue')

Or you just create a colors list with as many colors as you have lines.

Via get_colors() you get the current colors. If there are less colors, then lines, the colors get repeated. To change the color of a particular line, the full array of colors needs to be created, after which particular colors can be altered.

The following example changes the 11th line:

import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
import numpy as np

lines = plt.vlines(np.arange(16), np.random.rand(16), np.random.rand(16) + 5,
                   colors=['lime', 'gold', 'crimson'], lw=5)

# lines = plt.gca().collections[0]
colors = lines.get_colors()
num_colors = len(colors)
num_lines = len(lines.get_paths())
new_colors = np.tile(colors, ((num_lines + num_colors - 1) // num_colors, 1))
new_colors[10] = to_rgba('darkblue')
lines.set_colors(new_colors)

plt.show()

在 plt.vlines() 中改变一行的颜色

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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