如何在 Python 上的图表中同时使用字符串和数字标记 x&y 值

How to label x&y values using string and numbers at the same time in a graph on Python

我正在尝试使用 Python 来理解绘图。我想了解 "x_values" 在以下代码中做了什么以及它是如何工作的。我试图更改数字以查看它的影响,但它给了我 "shape dismatch" 错误提示 "objects cannot be broadcast to a single shape".

此外,我想知道如何使用图表中的方条,为它们中的每一个命名,同时仍然在轴上编号。

感谢 Ant 的帮助!

我驾驶 code/graphs 来自:Placing text values on axis instead of numeric values

谢谢。

我不知道哪里出了问题,所以我不知道我应该改变什么。

import matplotlib.pyplot as plt
import numpy as np
y_values = [0.1, 0.3, 0.4, 0.2]
text_values = ["word 1", "word 2", "word 3", "word 4"]
x_values = np.arange(1, len(text_values) + 1, 1)

plt.bar(x_values, y_values, align='center')
# Decide which ticks to replace.
new_ticks = ["word for " + str(y) if y != 0 else str(y) for y in y_values]
plt.yticks(y_values, new_ticks)
plt.xticks(x_values, text_values)
plt.show()

我希望方块的名称同时显示在轴上以及 x-y 轴上的编号(在轴上显示正方形,其名称位于其下方,并且编号仍在轴上)

在您的代码中,text_values 是一个包含 4 个字符串的列表。所以它有 4 个元素,这个列表的长度是 4。这是使用命令 len(text_values) 获得的。所以现在下面的命令

np.arange(1, len(text_values) + 1, 1)

变成

np.arange(1, 4 + 1, 1)

这意味着

np.arange(1, 5, 1)

这将生成从 1(第一个值)到第二个值减 1 (5 - 1 = 4) 的连续数字,步长为 1(第三个值)。所以你会得到

x_values = [1, 2, 3, 4]

现在您将这些值用作条形图的 x-argument。因此,您的条形图将位于 x = 1、x = 2、x = 3、x= 4。这就是您在图中看到的。