简体   繁体   English

由于空刻度,Matplotlib污染了x轴

[英]Matplotlib polluted x axis due to empty ticks

I'm trying to set customized xticks in matplotlib, following this question 我试图按照这个问题在matplotlib中设置自定义的Xticks

plot with custom text for x axis points 使用自定义文本绘制x轴点

However in the linked question the x axis has only 4 datapoints and they assign one label for each datapoint. 但是,在链接的问题中,x轴只有4个数据点,它们为每个数据点分配一个标签。 I have 100 datapoints representing a full sinusoidal period in radians and I only want to label the "interesting" points ( 0.0, π/4, π/2, 3π/2 ) 我有100个数据点,以弧度表示整个正弦周期,我只想标记“有趣的”点( 0.0, π/4, π/2, 3π/2

The closest I got to what I want is creating a list of 100 empty strings and then set the desired strings to the desired value. 我最想要的就是创建一个包含100个空字符串的列表,然后将所需的字符串设置为所需的值。 However the x axis gets very polluted due to the empty strings. 但是,由于空字符串,x轴会受到严重污染。

How can I get rid of this "pollution" and have only the desired position labeled? 我如何摆脱这种“污染”,而只标记所需的位置?

import matplotlib.pyplot as plt
import numpy as np

# generate 100 points in the range [0.0, 2*pi)
t = np.linspace(0.0, 2*np.pi, 101)[:-1] 
y = np.sin(t)

ticks = [''] * 100
ticks[0] = '0.0'
ticks[25] = 'π/4'
ticks[50] = 'π/2'
ticks[75] = '3π/2'

plt.xticks(t, ticks)

plt.plot(t, y)
plt.show()

在此处输入图片说明

You do seem to have a mistake in your display. 您的显示器似乎确实有误。 sin(pi/4) equals 0.78 and won't be where you put it on the graph. sin(pi/4)等于0.78 ,不会在图表上显示。

That said, the xticks function allows you to add custom ticks as a first parameter. 也就是说, xticks函数允许您将自定义刻度添加为第一个参数。 You don't have the use the linespace. 您没有使用行空间。 Do the following: 请执行下列操作:

ticks = [0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]
ticks_labels = ['0', 'π/2', 'π', '3π/2', '2π']


plt.xticks(ticks, ticks_labels)

and the result you get is 而你得到的结果是

在此处输入图片说明

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

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