Matplotlib:每个刻度线都有不同的颜色 [英] Matplotlib: Every tick in different color

查看:412
本文介绍了Matplotlib:每个刻度线都有不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用matplotlib(python 3.5)创建散点图,其中x轴上的每个刻度都具有不同的颜色。

I'm trying to create a scatter-plot with matplotlib (python 3.5) in which every tick on the x-axes has a different color. How is this possible?

例如,假设x标记是 Mo, Tu, We, Th, Fr,萨,苏。
现在我希望'Mo'为绿色,'Tu'为蓝色,等等...

For example let's say the x-ticks are 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'. Now I want 'Mo' to be green, 'Tu' to be blue, ect...

这是我的代码的一个非常简单的版本:

Here is a very simple version of my code:

from matplotlib import pyplot as plt
plt.figure(figsize=(16, 11))
x = [1, 2, 3, 4, 5, 6, 7]
y = [10, 12, 9, 10, 8, 11, 10]
plt.scatter(x, y)
plt.xticks(x, ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'])
plt.show()

我已经尝试过

my_colors = ['c', 'b', 'r', 'r', 'g', 'k', 'b']
plt.xticks(x, ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'], color=my_colors)

但这不起作用。

推荐答案

您可以遍历刻度标签(使用 plt.gca()。get_xticklabels()),并使用 .set_color()设置颜色。例如:

You can loop over the tick labels (using plt.gca().get_xticklabels()) and set their colors after they have been created, using .set_color(). For example:

from matplotlib import pyplot as plt
plt.figure(figsize=(16, 11))
x = [1, 2, 3, 4, 5, 6, 7]
y = [10, 12, 9, 10, 8, 11, 10]
plt.scatter(x, y)
plt.xticks(x, ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'])

my_colors = ['c', 'b', 'r', 'r', 'g', 'k', 'b']

for ticklabel, tickcolor in zip(plt.gca().get_xticklabels(), my_colors):
    ticklabel.set_color(tickcolor)

plt.show()

这篇关于Matplotlib:每个刻度线都有不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆