简体   繁体   中英

Matplotlib polluted x axis due to empty ticks

I'm trying to set customized xticks in matplotlib, following this question

plot with custom text for x axis points

However in the linked question the x axis has only 4 datapoints and they assign one label for each datapoint. 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 )

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. However the x axis gets very polluted due to the empty strings.

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.

That said, the xticks function allows you to add custom ticks as a first parameter. 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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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