
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Centering x-tick labels between tick marks in Matplotlib
To place labels between two ticks, we can take the following steps−
- Load some sample data, r.
- Create a copy of the array, cast to a specified type.
- Create a figure and a set of subplots using subplots() method.
- Plot date and r sample data.
- Set the locator of the major/minor ticker using set_major_locator() and set_minor_locator() methods.
- Set the locator of the major/minor formatter using set_major_locator() and set_minor_formatter() methods.
- Now, place the ticklabel at the center.
- To display the figure, use show() method.
Example
import numpy as np import matplotlib.cbook as cbook import matplotlib.dates as dates import matplotlib.ticker as ticker import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True with cbook.get_sample_data('aapl.npz') as fh: r = np.load(fh)['price_data'].view(np.recarray) r = r[-250:] date = r.date.astype('O') fig, ax = plt.subplots() ax.plot(date, r.adj_close) ax.xaxis.set_major_locator(dates.MonthLocator()) ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_formatter(dates.DateFormatter('%b')) for tick in ax.xaxis.get_minor_ticks(): tick.tick1line.set_markersize(0) tick.tick2line.set_markersize(0) tick.label1.set_horizontalalignment('center') imid = len(r) // 2 ax.set_xlabel(str(date[imid].year)) plt.show()
Output
- Related Questions & Answers
- Hiding major tick labels while showing minor tick labels in Matplotlib
- How to create a plot with tick marks between X-axis labels in base R?
- How to change the separation between tick labels and axis labels in Matplotlib?
- Overlapping Y-axis tick label and X-axis tick label in Matplotlib
- How to make longer subplot tick marks in Matplotlib?
- Change grid interval and specify tick labels in Matplotlib
- Show tick labels when sharing an axis in Matplotlib
- Turn off the left/bottom axis tick marks in Matplotlib
- How to increase/reduce the fontsize of X and Y tick labels in Matplotlib?
- How to rotate tick labels in a subplot in Matplotlib?
- Hide axis values but keep axis tick labels in matplotlib
- Getting empty tick labels before showing a plot in Matplotlib
- How to rotate X-axis tick labels in Pandas bar plot?
- How to turn off the upper/right axis tick marks in Matplotlib?
- Display tick marks in a JSlider with Java
Advertisements