问题:使用自定义文本绘制x轴点

我正在使用matplotlib和python绘制图,如下面的示例代码。

x = array([0,1,2,3])
y = array([20,21,22,23])
plot(x,y)
show()

因为它是上面x轴上的代码,所以我将看到绘制的值,0.0, 0.5, 1.0, 1.5即与参考x值相同的值。

无论如何,有没有将x的每个点映射到不同的字符串?因此,例如,我希望x轴显示月份名称(字符串Jun, July,...)或其他字符串,如人员姓名("John", "Arnold", ...)或时钟时间("12:20", "12:21", "12:22", ..)。

您知道我能做什么或要看什么功能吗?
对我而言,这有matplotlib.ticker帮助吗?

I am drawing a plot using matplotlib and python like the sample code below.

x = array([0,1,2,3])
y = array([20,21,22,23])
plot(x,y)
show()

As it is the code above on the x axis I will see drawn values 0.0, 0.5, 1.0, 1.5 i.e. the same values of my reference x values.

Is there anyway to map each point of x to a different string? So for example I want x axis to show months names( strings Jun, July,...) or other strings like people names ( "John", "Arnold", ... ) or clock time ( "12:20", "12:21", "12:22", .. ).

Do you know what I can do or what function to have a look at?
For my purpose could it be matplotlib.ticker of help?


回答 0

您可以使用pyplot.xticks手动设置xticks(和yticks):

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()


回答 1

这对我有用。X轴上的每个月

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。