python - 根据字典 matplotlib 中的值更改标签颜色

标签 python matplotlib

我有一个字典,其中包含作为标签的键和作为绘图颜色的值。使用以下示例:Change color of specific ticks at plot with matplotlib 。如何根据字典中的键更改标签颜色。请注意,标签可以在 x 轴上重复多次,并且可以是字符串,例如 labels = 'A'、'B'、'C'、'D'。

这是代码的一点修改:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,4))
ax.plot([1,2,3])
colors = {0.00 :'grey',0.25:'yellow',0.50:'brown',2.00:'red'}
for k, v in colors.items():
    ax.get_xticklabels()[k].set_color(v)

plt.show()

我希望绘图上的每个标签都与一种颜色相关联,但我得到一个带有此错误的普通绘图:TypeError:列表索引必须是整数或切片,而不是 float 。我正在尝试将其专门适应字符串标签。

最佳答案

一种解决方案是检查字典键中是否存在刻度标签。为了比较确切的值,我将键从浮点转换为字符串。我相信这对你来说应该不是问题。

P.S.:根据@ImportanceOfBeingEarnest 的评论,我想说这个答案假设该数字保持静态且未调整大小。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,4))
ax.plot([1,2,3])
colors = {'0.00' :'grey','0.25':'yellow','0.50':'brown','2.00':'red'}

fig.canvas.draw()

for xtic in ax.get_xticklabels():
    if xtic.get_text() in colors.keys(): # Change color if exist else not
        xtic.set_color(colors[xtic.get_text()])

plt.show()

enter image description here

关于python - 根据字典 matplotlib 中的值更改标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634402/

相关文章:

python - 在 genfromtxt 中使用转换器函数失败

python - Pylab : map labels to colors

Python:覆盖两个变量

python - 期待 ValueError : too many values to unpack but getting TypeError: 'bool' object is not iterable

pandas - 使用 seaborn 绘图时如何为色调参数指定多个变量?

python - 绘制不同索引长度的两条线图,在没有数据的情况下断开连接

python - MatPlotLib plot_surface : hidden lines appearing in PDF

python - Python脚本的SVN钩子(Hook)环境问题

python - 数据框和子图中的日期错误

python - 范围在 imshow() 中起什么作用?