gpt4 book ai didi

python - matplotlib 图表轴上每个标签的不同颜色?

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:39 24 4
gpt4 key购买 nike

是否可以为轴上的某些标签设置不同的颜色?

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_yticks([0,1,2])
ax1.set_yticklabels(['red','red', 'blue'], color='blue')

#What I would like to do
ax1.set_yticklabels(['red','red', 'blue'], colors=['red','red','blue']) <-- doesn't work

plt.show()

有没有办法实现我想要的?

incompletely colored axis labels

最佳答案

您可以使用这种方法访问 Tick 对象的所有属性:

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_yticks([0,1,2])
ax1.set_yticklabels(['red','red', 'blue'], color='blue')
colors=['red','red','blue']
for color,tick in zip(colors,ax1.yaxis.get_major_ticks()):
tick.label1.set_color(color) #set the color property

plt.show()

最后一个循环也可用于更改其他属性,例如标签的大小:

colors=['red','red','blue']
sizes=[10,20,30]
for color,size,tick in zip(colors,sizes,ax1.yaxis.get_major_ticks()):
tick.label1.set_color(color) #set the color
tick.label1.set_size(size) #set the size

最后一个例子的输出是这样的:

Varying size and color

关于python - matplotlib 图表轴上每个标签的不同颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21240195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com