简体   繁体   English

是否可以更改 matplotlib 的 vlines 中单行的颜色?

[英]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. 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绿色,第二个黄色,第三个红色,第四个绿色,第五个黄色等等。

Is there a way to access one line individually and change its color?有没有办法单独访问一行并更改其颜色?

You can plot that particular line separately:您可以单独使用 plot 该特定行:

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.或者,您只需创建一个 colors 列表,其中包含与行一样多的 colors。

Via get_colors() you get the current colors.通过get_colors()你得到当前的 colors。 If there are less colors, then lines, the colors get repeated.如果 colors 较少,则 colors 会重复。 To change the color of a particular line, the full array of colors needs to be created, after which particular colors can be altered.要更改特定行的颜色,需要创建 colors 的完整数组,之后可以更改特定的 colors。

The following example changes the 11th line:以下示例更改了第 11 行:

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() 中改变一行的颜色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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