Reputation: 6483
Following this I know that I can extract the xticks labels and positions using:
import matplotlib.pyplot as plt
plt.scatter(x_data, y_data)
locs, labels=plt.xticks()
the new variable labels
is a matplotlib.cbook.silent_list
, which
doesn't behave like a normal list.
Is there a way to access and modify any attribute value of the labels
elements?
Specifically I would like to know if I can select a subset of the labels (i.e. slice the silent_list) and modify a particular attribute for that subset.
Here is a toy example:
import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,2,3,4,5,6,7,8])
y=np.random.normal(0, 1, (8, 1))
plt.scatter(x, y)
locs, labels=plt.xticks()
As an example, let say I want to change the labels color to red for all but the first and last element of labels
; if I open one of the elements of the variable I can see that there is the attribute _color
with value k
, which I would like to change in r
:
I tried to slice it:
labels[1:-1]
But it returns:
Out[]: [Text(2,0,'2'), Text(4,0,'4'), Text(6,0,'6'), Text(8,0,'8')]
and this is as far as I managed to go.
I couldn't figure out a way to access the attribute and change its value.
NB: I am looking for a general way to access these attributes and change the value, I do not care about changing the labels color specifically. That's just an example.
Upvotes: 3
Views: 1371
Reputation: 39042
You might be interested in an alternative solution where you can choose which specific ticks you want to color. Here I have to loop from [1:-1]
because the first and the last ticks do not appear on the graph here but they appear in the labels
import numpy as np; np.random.seed(134)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x=np.array([1,2,3,4,5,6,7,8])
y=np.random.normal(0, 1, (8, 1))
plt.scatter(x, y)
fig.canvas.draw()
xticks = ax.get_xticklabels()
target_ticks = [1, 3, 6, len(xticks)-2]
for i, lab in enumerate(xticks[1:-1]):
if i+1 in target_ticks:
lab.set_color('r')
Upvotes: 2