我有一个数字未在x轴上显示正确的日期。可能是因为要显示的观测值太多,导致没有显示任何观测值。我不确定是否应该使用set_xticks
函数,但这会给我属性错误
AttributeError:模块'matplotlib.pyplot'没有属性'set_xticks'
我当前的代码是这样:
def plot_w(dataframe,ticker,benchmark):
# a. Printing highest observed values and corresponding date
max1 = data_df.loc[:, ticker].max()
max2 = data_df.loc[:, benchmark].max()
max1_date = data_df[data_df[ticker] == max1]['Date'].values[0]
max2_date = data_df[data_df[benchmark] == max2]['Date'].values[0]
print("The highest adjusted close price observed at: \n", ticker, ":", max1.round(2), "USD on the date ", max1_date,
"\n", benchmark, ":", max2.round(2), "USD on the date", max2_date)
# b. Setting up plot based on dropdown input
I = data_df.columns == ticker
mpl_figure = dataframe.loc[:, ['Date',ticker,benchmark]]
mpl_figure.plot(x='Date', y=[ticker,benchmark], style=['-b','-k'], figsize=(10, 5), fontsize=11, legend='true', linestyle = '-')
plt.ylabel("USD",labelpad=5)
plt.locator_params(axis='x', nbins=20)
title = "Adjusted close prices for " + ticker + " and " + benchmark
plt.title(title)
plt.set_xticks(data_df['Date'].values) # Code fails here
# c. Creating the widget for the plot
widgets.interact(plot_w,
dataframe = widgets.fixed(data_df),
ticker = widgets.Dropdown(
options=data_df.columns,
value='ATVI',
description='Company 1:',
disabled=False,
),
benchmark = widgets.Dropdown(
options=data_df.columns,
value='AAPL',
description='Company 2:',
disabled=False,
)
)
答案 0 :(得分:0)
set_xticks用于轴,如果要为图形设置刻度,则
plt.xticks(data_df['Date'].values)
答案 1 :(得分:0)
或者,您可以在函数中对轴对象进行以下尝试。这个想法是首先创建一个轴实例ax
,然后将其传递给plot命令。以后使用它来设置x刻度。
I = data_df.columns == ticker
fig, ax = plt.subplots(figsize=(10, 5))
mpl_figure = dataframe.loc[:, ['Date',ticker,benchmark]]
mpl_figure.plot(x='Date', y=[ticker,benchmark], style=['-b','-k'], ax=ax, fontsize=11, legend='true', linestyle = '-')
plt.ylabel("USD",labelpad=5)
plt.locator_params(axis='x', nbins=20)
title = "Adjusted close prices for " + ticker + " and " + benchmark
plt.title(title)
ax.set_xticks(data_df['Date'].values)
答案 2 :(得分:0)
模块 matplotlib.pyplot
没有set_xticks
函数,但是有xticks
函数。 (link to doc)。但是,类对象 matplotlib.axes.Axes
确实具有set_xticks
(link to doc)。
因此,代码中最简单的修复方法是
plt.xticks(data_df['Date'].values)
侧面说明:我不完全确定为什么matplotlib.pyplot会保留两个(几乎)效果相同但名称不同的函数。我想允许从模块或对象中调用它都是对MATLAB的模仿,但是在MATLAB中,函数名称是相同的。