user3493721 February 2016

How to plot tick values in-place

The following produces a plot in which y ticks are -1, -0.5, 0, 0.5, 1 and their scaling is plotted elsewhere, how do I force matplotlib to plot the tics in-place as -1e-9, -0.5-e9... so I don't have to search other parts of the plot for potential corrections to tick values?

import matplotlib.pyplot as plot
plot.plot([0, 1e-9, 0, -1e-9])
plot.show()

Google led me to plot.ticklabel_format(useOffset = False) but unfortunately that doesn't have a useScaling parameter.

Answers


jonchar February 2016

One way to do this is to get the y-axis tick values, format them as you like, and then add them back to the plot as y-axis tick labels.

import matplotlib.pyplot as plt
plt.plot([0, 1e-9, 0, -1e-9])

# pull out values for y-axis ticks
yticks = plt.gca().get_yticks()

# format new labels
new_yticklabels = ['{:0=4.2f}e-9'.format(tick/1e-9) for tick in yticks]

# set new labels
plt.gca().set_yticklabels(new_yticklabels)

plt.show()

Output

This may not be the best way, but it works. There is probably a way to do this using ticker formatters such as FuncFormatter.

This answer was helpful for getting the scientific notation formatting correct.

Post Status

Asked in February 2016
Viewed 3,093 times
Voted 11
Answered 1 times

Search




Leave an answer