Matplotlib文本不接受数组值

2024-06-12 21:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我尝试的代码:

import matplotlib.pyplot as plt
import numpy as np
bb = [1,2,3,4,5,6,7,8,9,10]
cc = ["red","red","yellow","red","green","red","red","green","red","red"]
tt = ["\u2714","\u2714""\u2718","\u2714","\u2718","\u2714","\u2714","\u2718","\u2714","\u2714"]
x1=np.arange(10)
x2=np.arange(10)
fig = plt.figure()
fig.set_size_inches(50,70)
ax1 = fig.add_subplot(331)

ax1.bar(np.arange(len(bb)), bb, color=cc,width=0.6)
text_applied = ax1.text(x1,2,tt,color=cc)

plt.show()

它以前没有任何问题。但不能处理文本。我得到以下错误:

^{pr2}$

请告诉我如何根据指定的颜色和x values显示文本。在


Tags: importasnpfigpltgreenredcc
2条回答

我不太明白你的问题。在^{}的文档中,我找不到将字符串数组馈入参数的可能性:

Definition : text(x, y, s, fontdict=None, withdash=False, **kwargs)

Type : Function of matplotlib.pyplot module

Add text to the axes.

Add the text s to the axes at location x, y in data coordinates.

Parameters

x, y :
scalars The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.
s : str The text.

所以我建议你

for x, t, c in zip(x1, tt, cc):
    ax1.text(x, 2, t, color=c)

我不确定您的预期输出是什么,但是如果您希望在每个条下面有不同颜色的符号,可以将它们设置为如下记号:

import matplotlib.pyplot as plt
import numpy as np

bb = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
cc = ["red", "red", "yellow", "red", "green", "red", "red", "green", "red", "red"]
tt = ["\u2714", "\u2714", "\u2718", "\u2714", "\u2718", "\u2714", "\u2714", "\u2718", "\u2714", "\u2714"]

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.bar(range(len(bb)), bb, color=cc, width=0.6)
ax1.set_xticks(range(len(bb)))
ax1.set_xticklabels(tt)
for xtick, color in zip(ax1.get_xticklabels(), cc):
    xtick.set_color(color)
plt.show()

输出:

Bars with colored ticks

顺便说一句,请注意,在您的代码中,tt在第二和第三个元素之间缺少一个逗号。在

相关问题 更多 >