|
|
|||||||||||||||||||||||||||||
|
pylab_examples_Examples 31_centered_ticklabels. |
H.Kamifuji . |
|
ティックラベルを中央に置くことは時々役に立ちます。 mpl は現在、ラベルをティックに関連付けており、ラベルは水平の配置プロパティを使用して 'center'、 'left'、または 'right' に整列させることができます。 しかし、これはダニの間にラベルの中心を置くのに役立ちません。 一つの解決策は、 "それに直面する"ことです。 マイナーティックを使用して、メジャーティックの中央にティックを配置します。 ここでは、ティックの中央にある月をラベル付けする例を示します
# sometimes it is nice to have ticklabels centered. mpl currently
# associates a label with a tick, and the label can be aligned
# 'center', 'left', or 'right' using the horizontal alignment property:
#
#
# for label in ax.xaxis.get_xticklabels():
# label.set_horizontalalignment('right')
#
#
# but this doesn't help center the label between ticks. One solution
# is to "face it". Use the minor ticks to place a tick centered
# between the major ticks. Here is an example that labels the months,
# centered between the ticks
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
# load some financial data; apple's stock price
fh = cbook.get_sample_data('aapl.npy.gz')
try:
# Python3 cannot load python2 .npy files with datetime(object) arrays
# unless the encoding is set to bytes. However this option was
# not added until numpy 1.10 so this example will only work with
# python 2 or with numpy 1.10 and later.
r = np.load(fh, encoding='bytes')
except TypeError:
r = np.load(fh)
fh.close()
r = r[-250:] # get the last 250 days
fig, ax = plt.subplots()
ax.plot(r.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(r.date[imid].year))
plt.show()
|
当方の環境では、動作しない。出力 msg は、下記$ py centered_ticklabels.py Traceback (most recent call last): File "centered_ticklabels.py", line 22, inPython 3.11.2 見直しました。上記のコードでは、下記のエラーが発生します。 Traceback (most recent call last): File "_:\centered_ticklabels.py", line 22, in <module> fh = cbook.get_sample_data('aapl.npy.gz') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\_____\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib\cbook\__init__.py", line 530, in get_sample_data return gzip.open(path) ^^^^^^^^^^^^^^^ File "C:\Users\_____\AppData\Local\Programs\Python\Python311\Lib\gzip.py", line 58, in open binary_file = GzipFile(filename, gz_mode, compresslevel) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\_____\AppData\Local\Programs\Python\Python311\Lib\gzip.py", line 174, in __init__ fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\_____\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\matplotlib\\mpl-data\\sample_data\\aapl.npy.gz' matplotlib 内部のエラーのようです。matplotlib の改修(先祖帰りバグの改修)を待つしかない。 Python 3.11.6 (matplotlib 3.7.1) では、下記のようなエラーがあり、実行できない。 Traceback (most recent call last): File "M:\______\centered_ticklabels.py", line 22, inPython 3.12.0 (matplotlib 3.8.1) では、下記のようなエラーがあり、実行できない。 Traceback (most recent call last): File "E:\______\centered_ticklabels.py", line 22, inPython 3.11.6 (matplotlib 3.7.1) 及び Python 3.12.0 (matplotlib 3.8.1) で、見直し中、新しいサンプル(ticks-centered-ticklabels-py) を見つけ、下記のコードで、正常に実行できました。
"""
==============================
Centering labels between ticks
==============================
Ticklabels are aligned relative to their associated tick. The alignment
'center', 'left', or 'right' can be controlled using the horizontal alignment
property::
for label in ax.get_xticklabels():
label.set_horizontalalignment('right')
However, there is no direct way to center the labels between ticks. To fake
this behavior, one can place a label on the minor ticks in between the major
ticks, and hide the major tick labels and minor ticks.
Here is an example that labels the months, centered between the ticks.
"""
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker
# Load some financial data; Google's stock price
r = cbook.get_sample_data('goog.npz')['price_data']
r = r[-250:] # get the last 250 days
fig, ax = plt.subplots()
ax.plot(r["date"], r["adj_close"])
ax.xaxis.set_major_locator(dates.MonthLocator())
# 16 is a slight approximation since months differ in number of days.
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
# Remove the tick lines
ax.tick_params(axis='x', which='minor', tick1On=False, tick2On=False)
# Align the minor tick label
for label in ax.get_xticklabels(minor=True):
label.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(r["date"][imid].item().year))
plt.show()
Python 3.11.6 (matplotlib 3.7.1) では、下記のようなエラーがあり、実行できない。
M:\______\centered_ticklabels_2.py:27: MatplotlibDeprecationWarning:
In a future release, get_sample_data will automatically load numpy arrays.
Set np_load to True to get the array and suppress this warning.
Set asfileobj to False to get the path to the data file and suppress this warning.
r = cbook.get_sample_data('goog.npz')['price_data']
Traceback (most recent call last):
File "M:\______\centered_ticklabels_2.py", line 27, in
Python 3.12.0 (matplotlib 3.8.1) では、正常実行です。![]() |
|
pylab_examples_Examples code: centered_ticklabels.py ticks-centered-ticklabels-py |
|