I'm new to matplotlib and trying to find out how can I change formatting only selected x tick labels. For simplicity, I attached below simple code and chart. How can I change font color of only last x tick label(5.0 in this example)?
Code
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [50, 40, 60, 70, 50])
plt.show()
Minor tick labels can be turned on by setting the minor formatter. MultipleLocator places ticks on multiples of some base. StrMethodFormatter uses a format string (e.g., '{x:d}' or '{x:1.2f}' or '{x:1.1f} cm' ) to format the tick labels (the variable in the format string must be 'x' ).
Still, if we want only the first three values of the x-axis to visualize, you can use this xlim() and ylim() function to set a limit for the x-axis and y-axis of the plot and then use the locate param to reduce the number of ticks.
Set the figure size and adjust the padding between and around the subplots. Create lists for height, bars and y_pos data points. Make a bar plot using bar() method. To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2.
You can obtain the xticklabels via ax.get_xticklabels()
. This returns a list of matplotlib.text.Text
instances. You can then select one of them and use text.set_color("red")
to colorize it.
ax.get_xticklabels()[-2].set_color("red")
The problem is that it's not intuitively clear which of the elements would be the one we are looking for. In this case it's the second last, since there is an empty ticklabel at the very end of the list. This may require to test a bit, or print them out before setting them. Also, if the plot is resized, such that more ticklabels appear on the axis, the formatted label might suddenly carry a different number than before. Such cases would require a bit more work to account for.
text
instance you like,
ax.get_xticklabels()[-2].set_color("white")
ax.get_xticklabels()[-2].set_fontsize(14)
ax.get_xticklabels()[-2].set_weight("bold")
ax.get_xticklabels()[-2].set_bbox(dict(facecolor="red", alpha=0.9))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With