## 2018年10月26日 星期五

### [ Python 常見問題 ] matplotlib - Changing the “tick frequency” on x or y axis in matplotlib?

Source From Here
Question
I am trying to fix how python plots my data.
Say
1. x = [0,5,9,10,15]
and
1. y = [0,1,2,3,4]
Then I would do:
1. matplotlib.pyplot.plot(x,y)
2. matplotlib.pyplot.show()
and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?

How-To
You could explicitly set where you want to tick marks with plt.xticks:
1. plt.xticks(np.arange(min(x), max(x)+1, 1.0))
For example,
1. import numpy as np
2. import matplotlib.pyplot as plt
3.
4. x = [0,5,9,10,15]
5. y = [0,1,2,3,4]
6. plt.plot(x,y)
7. plt.xticks(np.arange(min(x), max(x)+1, 1.0))
8. plt.show()
np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints. The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set:
1. start, end = ax.get_xlim()
2. ax.xaxis.set_ticks(np.arange(start, end, stepsize))
The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,
1. ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
Here's a runnable example:
1. import numpy as np
2. import matplotlib.pyplot as plt
3. import matplotlib.ticker as ticker
4.
5. x = [0,5,9,10,15]
6. y = [0,1,2,3,4]
7. fig, ax = plt.subplots()
8. ax.plot(x,y)
9. start, end = ax.get_xlim()
10. ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
11. ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
12. plt.show()

### [ Py DS ] Ch5 - Machine Learning (Part2)

Source From  Here   Introducing Scikit-Learn   There are several Python libraries that provide solid implementations of a range of machin... 