matplotlib의 날짜 눈금 및 회전
matplotlib에서 날짜 눈금을 회전시키는 데 문제가 있습니다. 작은 샘플 프로그램은 다음과 같습니다. 마지막에 진드기를 회전하려고하면 진드기가 회전하지 않습니다. 주석 'crashes'에 표시된대로 진드기를 회전하려고하면 matplot lib가 충돌합니다.
이것은 x- 값이 날짜 인 경우에만 발생합니다. 내가 변수로 대체하는 경우 dates
변수와 t
의 통화에서을 avail_plot
의 xticks(rotation=70)
호출은 잘 내부를 작동합니다 avail_plot
.
어떤 아이디어?
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
def avail_plot(ax, x, y, label, lcolor):
ax.plot(x,y,'b')
ax.set_ylabel(label, rotation='horizontal', color=lcolor)
ax.get_yaxis().set_ticks([])
#crashes
#plt.xticks(rotation=70)
ax2 = ax.twinx()
ax2.plot(x, [1 for a in y], 'b')
ax2.get_yaxis().set_ticks([])
ax2.set_ylabel('testing')
f, axs = plt.subplots(2, sharex=True, sharey=True)
t = np.arange(0.01, 5, 1)
s1 = np.exp(t)
start = dt.datetime.now()
dates=[]
for val in t:
next_val = start + dt.timedelta(0,val)
dates.append(next_val)
start = next_val
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
plt.subplots_adjust(hspace=0, bottom=0.3)
plt.yticks([0.5,],("",""))
#doesn't crash, but does not rotate the xticks
#plt.xticks(rotation=70)
plt.show()
객체 지향이 아닌 접근 방식을 선호하는 경우 두 개의 avail_plot 호출 직전에 plt.xticks (rotation = 70)을 이동하십시오.
plt.xticks(rotation=70)
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
레이블을 설정하기 전에 회전 속성을 설정합니다. 여기에 두 개의 축이 있기 때문에 두 개의 플롯을 만든 후에 plt.xticks가 혼동됩니다. plt.xticks가 아무것도하지 않는 시점에서 plt.gca ()는 수정하려는 축을 제공 하지 않으므로 현재 축에 작용하는 plt.xticks가 작동하지 않습니다.
plt.xticks를 사용하지 않는 객체 지향 접근 방식의 경우
plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
두 개의 avail_plot 호출 후 . 올바른 축의 회전을 구체적으로 설정합니다.
matplotlib 2.1 이상에서 작동하는 솔루션
tick_params
눈금 속성을 변경할 수 있는 좌표축 메서드 가 있습니다. 또한 축 방법으로 존재합니다set_tick_params
ax.tick_params(axis='x', rotation=45)
또는
ax.xaxis.set_tick_params(rotation=45)
As a side note, the current solution mixes the stateful interface (using pyplot) with the object-oriented interface by using the command plt.xticks(rotation=70)
. Since the code in the question uses the object-oriented approach, it's best to stick to that approach throughout. The solution does give a good explicit solution with plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
An easy solution which avoids looping over the ticklabes is to just use
This command automatically rotates the xaxis labels and adjusts their position. The default values are a rotation angle 30° and horizontal alignment "right". But they can be changed in the function call
fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')
The additional bottom
argument is equivalent to setting plt.subplots_adjust(bottom=bottom)
, which allows to set the bottom axes padding to a larger value to host the rotated ticklabels.
So basically here you have all the settings you need to have a nice date axis in a single command.
A good example can be found on the matplotlib page.
Another way to applyhorizontalalignment
and rotation
to each tick label is doing a for
loop over the tick labels you want to change:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
hours_value = np.random.random(len(hours))
days_value = np.random.random(len(days))
fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
axs[0].plot(hours,hours_value)
axs[1].plot(days,days_value)
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
label.set_rotation(30)
label.set_horizontalalignment("right")
And here is an example if you want to control the location of major and minor ticks:
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
axs[0].plot(hours,np.random.random(len(hours)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.HourLocator(byhour = range(0,25,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[0].xaxis.set_major_locator(x_major_lct)
axs[0].xaxis.set_minor_locator(x_minor_lct)
axs[0].xaxis.set_major_formatter(x_fmt)
axs[0].set_xlabel("minor ticks set to every hour, major ticks start with 00:00")
axs[1].plot(days,np.random.random(len(days)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.DayLocator(bymonthday = range(0,32,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[1].xaxis.set_major_locator(x_major_lct)
axs[1].xaxis.set_minor_locator(x_minor_lct)
axs[1].xaxis.set_major_formatter(x_fmt)
axs[1].set_xlabel("minor ticks set to every day, major ticks show first day of month")
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
label.set_rotation(30)
label.set_horizontalalignment("right")
참고URL : https://stackoverflow.com/questions/11264521/date-ticks-and-rotation-in-matplotlib
'programing tip' 카테고리의 다른 글
iOS 7 sizeWithAttributes : sizeWithFont : constrainedToSize 대체 (0) | 2020.06.28 |
---|---|
pandas를 사용하여 파이썬으로 Excel 파일 읽기 (0) | 2020.06.28 |
푸시 컨트롤러에서 RootViewController를 어떻게 얻습니까? (0) | 2020.06.28 |
WHERE 절에서 대소 문자 구분 검색을 수행하는 방법 (SQL Server를 사용 중)? (0) | 2020.06.28 |
간단하게 유지하고 쿼리에서 여러 CTE를 수행하는 방법 (0) | 2020.06.28 |