在双胞胎图的x轴上设置日期间隔

时间:2017-10-17 12:51:20

标签: python matplotlib plot bar-chart linechart

我正在尝试使用matplotlib绘制在x轴上具有日期的双y轴图表

日期是每天,但我希望x轴标签显示每10天左右的日期。

这在单个y轴图上工作正常,如下所示:

x = z['date']
y = z['volume']
#plt.bar(x,y, 0.2, color = 'blue')


fig, ax=plt.subplots()
ax = plt.subplot(111)

ax.bar(x,y, width= 0.3)
ax.xaxis.set_major_locator(DayLocator(bymonthday = range(1,32), interval = 
10))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
plt.xticks(rotation = 45)   

plt.show()

但我似乎无法用两个y轴显示它们。我目前正在尝试以下代码:

以下是Dataframe DV的示例:

DV
Out[291]: 
   volume  price  Date   DayDate
0    9100   6.00  1990  736018.0
1   12796   7.90  1984  736082.0
2   14465   7.56  2007  736088.0
3   15000   7.45  1992  736103.0

# note, the index of the df is actually the same as the date column 

一行中的条目示例 指数 2016-02-24,9107.4540,6.00,2016-02-24,736018.0

现在绘制双轴图的代码:

fig, ax=plt.subplots()
ax = plt.subplot(111)

x = DV['Date'] # nb ; DV['Date'] = date2num(pd.to_datetime(DV ['Date']).tolist())
y = DV['Volume']
y1 = DV['price']

ax.bar(x,y, width = 0.8)

ax.xaxis.set_major_locator(DayLocator(bymonthday = range(1,32), interval =  10))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))

ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), DV['price'], marker = 'o', linestyle = '-', color 
= 'r')

ax2.legend(loc='upper right')
ax.legend(loc='upper left')
ax.set_ylabel('Volume ')
ax2.set_ylabel('price')

ax.set_xlabel('Date')

plt.xticks(rotation = 45)
ax.set_title('daily price v. volume')
ax.set_ylim(0,1.3*DV["volume"].max())
ax2.set_ylim(0,1.3*DV["price"].max())

ax2.grid(False)
plt.autoscale()
plt.show()

任何帮助将不胜感激!

0 个答案:

没有答案
相关问题