Reputation: 222
I plot image using matplotlib, the X axis have pixels on it - from 1 to image size by X axis, for example [1,1000], which is correspond to my physical value range
k1_range = [2.11, 6.33]
I need labels to be shown along X axis, not pixels, but my actual physical value. If I will use something like
numpy.linspace(k1_range[0], k1_range[1], 5)
I will get some "ugly" labels
array([ 2.11 , 3.165, 4.22 , 5.275, 6.33 ])
I need them to be nice, like
array([ 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. ])
matplotlib can generate such nice looking ticks when ploting curve with auto ticks, but I see no simple way to specify custom range for this nice-ticks-auto-generation.
I had to use this code to make nice ticks, it's seems to be working, but it is time wasting to write bugged code to do something that is already done in matplotlib
k1_range=[2.11, 6.33]
KTickCount = 5
KTickStep = numpy.abs((k1_range[1]-k1_range[0])) / KTickCount
Digits = numpy.floor(numpy.log10(KTickStep)+1)-1
KTickStep = (KTickStep/10**Digits)
if KTickStep < 2:
KTickStep = 1
elif KTickStep < 2.5:
KTickStep = 2
elif KTickStep < 5:
KTickStep = 2.5
else:
KTickStep = 5
KTickStep = KTickStep * 10**Digits
Digits = numpy.floor(numpy.log10(numpy.max(k1_range))+1)-1
KTicks = numpy.arange(numpy.ceil(k1_range[0]/KTickStep)*KTickStep, k1_range[1], KTickStep)
print(KTicks)
Output:
[ 2.5 3. 3.5 4. 4.5 5. 5.5 6. ]
How to get nice (round to 1, 2, 2.5, 5) tick positions when plotting with matplotlib?
Upvotes: 1
Views: 757
Reputation: 222
Someone on matplotlib github give me answer to this question, which is working nicely https://github.com/matplotlib/matplotlib/issues/6975#issuecomment-242579370
import matplotlib
import matplotlib.ticker
...
l = matplotlib.ticker.AutoLocator()
l.create_dummy_axis()
l.tick_values(-10, 15.5)
:
array([-10., -5., 0., 5., 10., 15., 20.])
Upvotes: 1