问题描述
使用matplotlib,是否可以更改轴上特定刻度的颜色?
Using matplotlib, is there an option to change the color of specific ticks on the axis?
我有一个简单的图,按天显示一些值,我需要将某些天标记为特殊"日子,所以我想用不同的颜色标记这些天,但并非所有的刻度都只是特定的.
I have a simple plot that show some values by days, and i need to mark some days as 'special' day so i want to mark these with a different color but not all ticks just some specific.
谢谢
推荐答案
您可以使用 ax.get_xticklabels()
.这实际上是文本对象的列表.结果,您可以在元素上使用 set_color()
该列表以更改颜色:
You can get a list of tick labels using ax.get_xticklabels()
. This is actually a list of text objects. As a result, you can use set_color()
on an element of that list to change the color:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5,4))
ax.plot([1,2,3])
ax.get_xticklabels()[3].set_color("red")
plt.show()
或者,您可以使用plt.gca()
获取当前轴.下面的代码将给出相同的结果
Alternatively, you can get the current axes using plt.gca()
. The below code will give the same result
import matplotlib.pyplot as plt
plt.figure(figsize=(5,4))
plt.plot([1, 2, 3])
plt.gca().get_xticklabels()[3].set_color("red")
plt.show()
这篇关于使用matplotlib更改图上特定刻度线的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!