2017-08-08 19 views
1

matplotlib.pyplotを使用してxticksを次の画像のように数ヶ月間ずっと2行に並べたプロットが必要です。私はそのプロットを、ちょうどdataframe.plot()を使って、すなわち最も簡単なパンダのプロットをしました。 enter image description herematplotlibを使用して2行のラベルスティックでプロットする

私は(私は別のサブプロットを追加する必要があり、それがdataframe.plot()を使用しない理由であるので)私はxticksラベルの設定の前に取得することができますどのように、このコードを使用して、プロットを行うと?私は、これは私はあなたがあなたが望むものに近い得ることができますmatplotlib.dates.DateFormattermatplotlib.tickerを使用しますが、私は正しい設定に

答えて

1

を見つけることができませんしようとしたプロット enter image description here

のラベルをxticks取得

import matplotlib.pyplot as plt 
figure, ax = plt.subplots() 
ax.plot(xdata, ydata) 

メジャーおよびマイナーロケータとDateFormatterこのように:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.dates 

dr= pd.date_range("2014-01-01", "2017-06-30", freq="D") 
df = pd.DataFrame({"dates":dr, "num":np.cumsum(np.random.randn(len(dr)))}) 
df["dates"] = pd.to_datetime(df["dates"]) 

fig, ax = plt.subplots() 
ax.plot(df.dates, df.num) 

ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator()) 
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator([1,7])) 
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%b\n%Y")) 
plt.show() 

のみへ

1月のために年間示しているが、他の月の、あなたはその後、DateFormatter

class MyMonthFormatter(matplotlib.dates.DateFormatter): 
    def __init__(self, fmt="%b\n%Y", fmt2="%b", major=[1], tz=None): 
     self.fmt2 = fmt2 
     self.major=major 
     matplotlib.dates.DateFormatter.__init__(self, fmt, tz=tz) 
    def __call__(self, x, pos=0): 
     if x == 0: raise ValueError('Error') 
     dt = matplotlib.dates.num2date(x, self.tz) 
     if dt.month in self.major: 
      return self.strftime(dt, self.fmt) 
     else: 
      return self.strftime(dt, self.fmt2) 

ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator()) 
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator([1,7])) 
ax.xaxis.set_major_formatter(MyMonthFormatter()) 
plt.show() 

enter image description here

をサブクラス化する必要があるかもしれません
関連する問題