matplotlib 用单独指定的颜色绘制每个刻度线

ukqbszuj  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(92)

我试图改变我的图中的刻度线的颜色,我想根据带有颜色代码的字符串列表分配颜色。我遵循以下方法,但我不明白为什么这不起作用:

import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = np.sin(x)
y2 = np.tan(x)
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, y)
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, y2)
colors = ['b', 'g', 'r', 'c', 'm', 'y']
ax1.set_xticks(x)
for tick, tickcolor in zip(ax1.get_xticklines(), colors):
    tick._color = tickcolor
plt.show()

有谁知道如何正确执行这个命令吗?

xeufq47z

xeufq47z1#

正如评论中所指出的,tick._color/tick.set_color(tickcolor)由于bug而无法工作:
使用tick.set_markeredgecolor是解决方法,但它似乎不是唯一的问题。ax1.get_xticklines()在每两个项目上产生实际的刻度线,因此您应该只zip这些:

for tick, tickcolor in zip(ax1.get_xticklines()[::2], colors):
    tick.set_markeredgecolor(tickcolor)

输出量:

  • 注意:还可以更改刻度宽度,以更好地显示颜色。*

完整代码:

import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = np.sin(x)
y2 = np.tan(x)
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, y)
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, y2)
colors = ['b', 'g', 'r', 'c', 'm', 'y']
ax1.set_xticks(x)
for tick, tickcolor in zip(ax1.get_xticklines()[::2], colors):
    tick.set_markeredgecolor(tickcolor)
    tick.set_markeredgewidth(4)
plt.show()
oaxa6hgo

oaxa6hgo2#

一个粗略的方法是这样的:

import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = np.sin(x)
y2 = np.tan(x)
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, y)
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, y2)
colors = ['b', 'g', 'r', 'c', 'm', 'y']
ax1.set_xticks(x)
for tick, tickcolor in zip(ax1.xaxis.majorTicks, colors):
    tick._apply_params(color=tickcolor)
plt.show()

我相信它是粗略的,因为我依赖于一个“私有”方法(其名称以 * 下划线 * 开头)。

相关问题