根据标签字符串设置 xtick 标签颜色
set xtick label colors based on label string
我有一个带有标签列表的图。我想做的是根据字符串对每个标签进行颜色编码。因此,例如,所有带有字符串 ':Q_D' 的标签都将指代四极杆并且应该具有特定的颜色。用于着色的其他子字符串是水平和垂直校正器磁铁的“:DCH_D”和“:DCV_D”。
我看到您可以使用以下方法更改所有 xtick 标签的颜色:plt.xticks(color='r')
但我想让它们单独着色。这可能吗?
您可以遍历刻度标签,检查它们是否包含给定的字符串,并设置颜色:
from matplotlib import pyplot as plt
import numpy as np
from random import choice, randint
# first create some test data
labels = [f"REA_BTS{randint(25, 35)}:{choice(['DCV_D', 'DCH_D', 'Q_D'])}{randint(1100, 1500)}:I_CSET"
for _ in range(20)]
# create the plot
fig, ax = plt.subplots(figsize=(12, 6))
for _ in range(7):
ax.plot(labels, np.random.randn(20).cumsum())
ax.tick_params(axis='x', labelrotation=90)
ax.margins(x=0.01) # less whitespace inside the plot left and right
plt.tight_layout()
# set the colors of the tick labels; note that the tick labels are
# only filled in after plt.tight_layout() or after a draw
for t in ax.get_xticklabels():
txt = t.get_text()
print(t.get_text())
if 'Q_D' in txt:
t.set_color('tomato')
elif 'DCV_D' in txt:
t.set_color('cornflowerblue')
elif 'DCH_D' in txt:
t.set_color('lime')
plt.show()
我有一个带有标签列表的图。我想做的是根据字符串对每个标签进行颜色编码。因此,例如,所有带有字符串 ':Q_D' 的标签都将指代四极杆并且应该具有特定的颜色。用于着色的其他子字符串是水平和垂直校正器磁铁的“:DCH_D”和“:DCV_D”。
我看到您可以使用以下方法更改所有 xtick 标签的颜色:plt.xticks(color='r')
但我想让它们单独着色。这可能吗?
您可以遍历刻度标签,检查它们是否包含给定的字符串,并设置颜色:
from matplotlib import pyplot as plt
import numpy as np
from random import choice, randint
# first create some test data
labels = [f"REA_BTS{randint(25, 35)}:{choice(['DCV_D', 'DCH_D', 'Q_D'])}{randint(1100, 1500)}:I_CSET"
for _ in range(20)]
# create the plot
fig, ax = plt.subplots(figsize=(12, 6))
for _ in range(7):
ax.plot(labels, np.random.randn(20).cumsum())
ax.tick_params(axis='x', labelrotation=90)
ax.margins(x=0.01) # less whitespace inside the plot left and right
plt.tight_layout()
# set the colors of the tick labels; note that the tick labels are
# only filled in after plt.tight_layout() or after a draw
for t in ax.get_xticklabels():
txt = t.get_text()
print(t.get_text())
if 'Q_D' in txt:
t.set_color('tomato')
elif 'DCV_D' in txt:
t.set_color('cornflowerblue')
elif 'DCH_D' in txt:
t.set_color('lime')
plt.show()