У меня возникла проблема. Учитывая, что для линейного графика я не могу правильно добавить отметки для равномерного отображения и за пределами последней точки данных. Я также хочу, чтобы значения ytick округлялись до десятков.
Я пробовал это:
- Используйте np.arange(), но это не сработало. Диапазон данных варьируется в зависимости от набора данных, и я не смог это понять.
- Используйте условие, чтобы проверить, находится ли максимальное значение выше или ниже 1000, чтобы помочь с интервалами. распределение. Я не уверен, что это хороший подход, поскольку я предположил, что пороговым значением является 1000. Затем я установил nbins=7, чтобы посмотреть, как это выглядит. Я не могу понять, как сделать значение nbins динамическим, чтобы ячейки были равномерно распределены по оси Y.
def build_multiple_line_graphs(df, inception_date, line_graph_path):
"""Builds line graphs for market data."""
os.makedirs(line_graph_path, exist_ok=True)
inception_date = datetime.strptime(inception_date, '%Y-%m-%d')
# Plot the time series
fig, ax = plt.subplots()
# setting the size of the line graph
dpi=150
desired_width_pixels = 563
desired_height_pixels = 169
fig.set_size_inches(desired_width_pixels / dpi, desired_height_pixels / dpi)
fig.tight_layout()
df.plot(kind = 'line', ax=ax, y=complex, color='#0092BC')
# Add a horizontal line at y=0
ax.axhline(y=0, color='#005871', linestyle='-', label='Horizontal Line')
# Set the background color
ax.set_facecolor('#F0F8FF')
fig.patch.set_facecolor('#e4f2ff')
# removing frame from the graph
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
# set custom y-axis label
max_y = max(df)
if max_y < 1000:
max_y = 100*math.ceil(round(max_y/100)) if max_y > 0 else 1
else:
max_y = round((1000*math.ceil(max_y/1000))) if max_y > 0 else 1
new_max_y = max_y + (max_y//3)
increment = round(max_y/5)
ax.set_yticks(np.arange(0, max_y, increment))
plt.locator_params(axis='y', nbins=7)
# here is where I tried np.arange with no success
#ax.yaxis.set_major_locator(ticker.MultipleLocator(increment))
#ax.set_yticks(np.arange(0,df+1, increment))
#plt.yticks(np.arange(0,max(df)+increment, increment))
#start, end = ax.get_ylim()
#stepsize = end/5
#ax.yaxis.set_ticks(np.arange(0, end+1, 100))
ax.set_ylim(ymin=0)
# set custom x-axis label every 5 years
ax.xaxis.set_major_locator(mdates.YearLocator(5))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.xticks(rotation=0, ha='center')
ax.grid(axis='y', color='gray')
# Customize the plot
ax.legend().remove()
ax.tick_params(axis='both', labelsize=8, left = False, bottom = False)
ax.set_xlabel(None)
ax.fill_between(df.index, df, 0, color='#FFFFFF', alpha=0.8)
ax.set_xlim(df.index[0], df.index[-1])
# formating the inception line
ax.axvline(inception_date, color = '#0092BC', linestyle='dotted', label='Inception Date')
ax.text(inception_date, 25, 'Inception Date', rotation=90, rotation_mode='anchor', transform_rotates_text= True, fontsize=6)
inception_date_text = inception_date.strftime("%m/%d/%y")
ax.annotate(inception_date_text, xy=(inception_date, -1), xytext=(-15, -18), fontsize=8,
textcoords='offset points', ha='center', va='bottom')
# saving the plot
plt.gcf() # get current figure
fig_size = plt.gcf().get_size_inches()
plt.gcf().set_size_inches(fig_size[0]*2, fig_size[1]*2)
plt.savefig(os.path.join(line_graph_path, 'name_linegraph.png'), bbox_inches='tight',dpi=300)
# no display of the plot needed
plt.close()
Подробнее здесь: https://stackoverflow.com/questions/793 ... enly-distr
Мобильная версия