简体   繁体   English

如何向现有的 x-ticks label matplotlib 添加额外的符号?

[英]How to add extra sign to already existing x-ticks label matplotlib?

Currently, my histogram plot's x-tick labels are [200.目前,我的直方图的 x-tick 标签是 [200. 400. 600. 800. 1000. 1200. 1400.]. 400. 600. 800. 1000. 1200. 1400.]。 It represents the rate in dollars.它代表以美元为单位的汇率。 I want to add $ in prefix of these ticks like [$200 $400 $600 $800 $1000 $1200 $1400].我想在这些刻度的前缀中添加 $,例如 [$200 $400 $600 $800 $1000 $1200 $1400]。

I tried this axs.xaxis.get_majorticklocs() to fetch x-tick labels and axs.xaxis.set_ticks([f"${amount:.0f}" for amount in axs[0, 1].xaxis.get_majorticklocs()]) to set the updated one.我试过这个axs.xaxis.get_majorticklocs()来获取 x-tick 标签和axs.xaxis.set_ticks([f"${amount:.0f}" for amount in axs[0, 1].xaxis.get_majorticklocs()])设置更新的。 I understand that It will throw error as x-tick labels are now string.我知道它会抛出错误,因为 x-tick 标签现在是字符串。

Need help.需要帮忙。 kindly assist how can I do this.请协助我该怎么做。

You can do it like this:你可以这样做:

x = [*range(200,1600,200)]
y = [*range(7)]
fig, ax = plt.subplots()
ax.plot(x,y)
ax.set_xticks(ticks=x, labels=[f"${num}" for num in x])

在此处输入图像描述

You can use automatic StrMethodFormatter like this:您可以像这样使用自动StrMethodFormatter

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))

# Use automatic StrMethodFormatter
ax.xaxis.set_major_formatter('${x:1.2f}')

plt.show()

在此处输入图像描述

You might be looking for set_xticklabels , which says:您可能正在寻找set_xticklabels ,它说:

Set the xaxis' labels with list of string labels.使用字符串标签列表设置 xaxis 的标签。

Here you want to set the ticks to [200. 400. 600. 800. 1000. 1200. 1400.]在这里,您要将刻度设置为[200. 400. 600. 800. 1000. 1200. 1400.] [200. 400. 600. 800. 1000. 1200. 1400.] and the labels to your string values to ensure it is all aligned. [200. 400. 600. 800. 1000. 1200. 1400.]和字符串值的标签,以确保它全部对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM