在fill_between中的条件不起作用的地方

时间:2019-01-02 17:39:08

标签: python matplotlib

尝试使用以下代码:

ax1.fill_between(date, closep, closep[0], where = closep > closep[0], facecolor = 'g', alpha = 0.3) 
ax1.fill_between(date, closep, closep[0], where = closep < closep[0], facecolor = 'r', alpha = 0.3)

这根本不起作用

我做了以下事情: 1.尝试仅运行“>”条件:它填充了整个图形 2.尝试仅运行'<'条件:它没有填满任何内容

import datetime as dt
import matplotlib.pyplot as plt
import pandas_datareader.data as web

start = dt.datetime(2000, 1, 1)
end = dt.datetime(2016, 12, 31)
df = web.DataReader('TWTR', 'yahoo', start, end)
df.reset_index(inplace = True)

stock = 'Twitter'

date = df['Date'].tolist()

closep = df['Close'].tolist()

fig = plt.figure()

ax1 = plt.subplot2grid((1,1), (0,0))
ax1.plot_date(date, closep, '-', label = 'Price')
ax1.fill_between(date, closep, closep[0], where = closep > closep[0], facecolor = 'g', alpha = 0.3) 
ax1.fill_between(date, closep, closep[0], where = closep < closep[0], facecolor = 'r', alpha = 0.3)

for label in ax1.xaxis.get_ticklabels():
 label.set_rotation(45)

ax1.grid(True)
ax1.xaxis.label.set_color('c')
ax1.yaxis.label.set_color('r')
plt.xlabel('date')
plt.ylabel('Close Price')
plt.title(stock)
plt.legend()
plt.show()

运行上面的代码,我得到:

result1: All Fill

我尝试了以下操作:

#ax1.fill_between(date, closep, closep[0], where = closep > closep[0], facecolor = 'g', alpha = 0.3) 
ax1.fill_between(date, closep, closep[0], where = closep < closep[0], facecolor = 'r', alpha = 0.3)

这给了我

result2: No Fill

接下来,我尝试了此操作

ax1.fill_between(date, closep, closep[0], where = closep > closep[0], facecolor = 'g', alpha = 0.3) 
#ax1.fill_between(date, closep, closep[0], where = closep < closep[0], facecolor = 'r', alpha = 0.3)

哪个给了我: result3: All Fill

理想情况下,closep [0]上方的颜色应为彩色,而其下方的颜色应为空白。

但是,一切都变满了。而且,仅运行'>'可以填充所有内容,而仅运行'<'条件则不能填充任何内容

我使用python2.7

1 个答案:

答案 0 :(得分:0)

尝试:

import datetime as dt
import matplotlib.pyplot as plt
import pandas_datareader.data as web

start = dt.datetime(2000, 1, 1)
end = dt.datetime(2016, 12, 31)
df = web.DataReader('TWTR', 'yahoo', start, end)
df.reset_index(inplace = True)

stock = 'Twitter'

date = df['Date'].tolist()

closep = df['Close'].tolist()

fig = plt.figure()

ax1 = plt.subplot2grid((1,1), (0,0))
ax1.plot_date(date, closep, '-', label = 'Price')
ax1.fill_between(date, closep, closep[0], where = [i > closep[0] for i in closep], facecolor = 'g', alpha = 0.3) 
ax1.fill_between(date, closep, closep[0], where = [i < closep[0] for i in closep] , facecolor = 'r', alpha = 0.3)

for label in ax1.xaxis.get_ticklabels():
 label.set_rotation(45)

ax1.grid(True)
ax1.xaxis.label.set_color('c')
ax1.yaxis.label.set_color('r')
plt.xlabel('date')
plt.ylabel('Close Price')
plt.title(stock)
plt.legend()
plt.show()

输出:

enter image description here