问题
I have plotted some data with Python and tried to change the ticks with FuncFormatter
. Now I want to change the segmentation into round numbers. I also want minor ticks in the same formation, in my case it would be a 1/x
segmentation. I want the scaling to spread. The pictures will help you to imagine my issue.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
x = np.array([805.92055,978.82006,564.88627,813.70311,605.73361,263.27184,169.40317])
y = np.array([10,9,8,7,6,3,2])
fig, ax = plt.subplots(figsize =(3.6,2.5))
plt.plot(1/x,y,linestyle ='None',marker='1')
a=0.001
b=0.005
plt.xlim(a,b)
def my_formatter_fun(x, p):
return "%.0f" % (1/x)
ax.get_xaxis().set_major_formatter(tick.FuncFormatter(my_formatter_fun))
How can I change the segmentaion so that I get something like this? I thought there could be a way to add my wishes in my_formatter_fun
but I don't know how. How could I add minor-ticks also in a 1/x
distribution? I tried plt.minorticks_on()
but this is not working, because they are in a linear position.
回答1:
The location of the ticks can be controlled with a matplotlib.ticker.Locator
. For 1/x
ticks, you need to define your own custom Locator:
class ReciprocalLocator(tick.Locator):
def __init__(self, numticks = 5):
self.numticks = numticks
def __call__(self):
vmin, vmax = self.axis.get_view_interval()
ticklocs = np.reciprocal(np.linspace(1/vmax, 1/vmin, self.numticks))
return self.raise_if_exceeds(ticklocs)
You can use it in your plot by calling
ax.get_xaxis().set_major_locator(ReciprocalLocator(numticks=4))
ax.get_xaxis().set_minor_locator(ReciprocalLocator(numticks=20))
This needs more tweaking to move the locations to nice numbers. For inspiration, have a look at the source code of matplotlib.ticker.MaxNLocator
.
来源:https://stackoverflow.com/questions/43872468/python-1-x-plot-scale-formatting-tick-position