连续几个小时,我一直在尝试更改x轴刻度频率。我希望每个数据点都有一个对应的刻度(或其他,至少三分之一)。
我的图表应该显示一段时间内售出的商品数量kolicina
和折扣百分比popust (%)
,这是每个季节的图表(为简单起见,我仅使用一个季节的图表)。
这是我的代码:
#Libraries
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
#Import data
data = pd.read_excel(r'C:\Users\dagejev\Downloads\export_20190719.xls', index_col=None)
#Select relevant data
data = data[['dan_id', 'sezona_id', 'popust_retka', 'kolicina', 'maloprodajna_cijena']]
#Add new column
data['popust (%)'] = data['popust_retka'] / (data['maloprodajna_cijena'] * data['kolicina'])
#Modifying data
data2 = data.reset_index().groupby(['sezona_id','dan_id'], as_index=True).agg({'kolicina' : 'sum', 'popust (%)' : 'mean'})
#x-axis data creation
xaxis = data2.reset_index().set_index('sezona_id')['dan_id']
## Convert from integer to datetime
xaxis.apply(str)
xaxis = xaxis.apply(pd.to_datetime, format='%Y%m%d')
#Clear figure just in case
plt.clf()
#Main: plotting
plt.figure()
fig, ax1 = plt.subplots()
main_color = 'black'
season_name = data2.reset_index()['sezona_id'].unique()[3]
#Plotting axis and visual adjustments
ax1.plot(xaxis.loc[season_name], data2.loc[season_name,'kolicina'], 'k-')
ax1.set_ylabel('količina', color=main_color)
ax1.tick_params('y', colors=main_color)
ax1.tick_params('x', colors=main_color) #x-axis ticks
ax1.xaxis_date()
ax1.set_title(season_name, color=main_color)
#Failed attempt at spacing ticks no. 1 - runs w/ no change
'''xi = [j for j in range(0, len(xaxis.loc[season_name]))]
plt.xticks(xi, xaxis.loc[season_name])'''
#Failed attempt at spacing ticks no. 2 - runs w/ no change
'''tick_spacing = 1
ax1.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))'''
# I also tried changing the index of the data (`kolicina` and `popust (%)`)
# series to datetime format just like this:
# `data2.reset_index()['dan_id'] = xaxis
# which resulted in
# `ValueError: cannot reindex a duplicate axis`
#Twin axis
x1 = ax1.twinx()
x1.plot(xaxis.loc[season_name], data2.loc[season_name,'popust (%)'], 'r-')
x1.set_ylabel('popust', color='r')
x1.tick_params('y', colors='r')
#Visual adjustments
fig.subplots_adjust(right=1.5, top=1.0, hspace=0.5)
fig.autofmt_xdate(rotation=33)
fig.patch.set_facecolor('xkcd:white')
plt.show()
产生了一些不相关的信息:
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
情节:
非常感谢您的帮助。
答案 0 :(得分:1)
只需在plt.xticks()中传递 x的值,然后使用'plt.gcf'设置x轴即可。 已经创建了一个随机数据框,并绘制了图形进行检查。
< / p>
plt.xticks(x,rotation=90)
fig = plt.figure(figsize=(8,5))
ax1 = fig.add_subplot(111)
ax1.plot(x, y, c='b', marker="s", label='y')
plt.legend(loc='upper left')
#plt.xticks(x,rotation=90)
#plt.xticks(range(len(x)))
plt.gca().margins(x=0)
plt.gcf().canvas.draw()
t_l = plt.gca().get_xticklabels()
maxsize = max([t.get_window_extent().width for t in t_l])
m = .2 # inch margin
s = maxsize/plt.gcf().dpi*len(x)+3*m
margin = m/plt.gcf().get_size_inches()[1]
plt.gcf().subplots_adjust(left=margin, right=0.8-margin)
plt.gcf().set_size_inches(s, plt.gcf().get_size_inches()[1])
plt.xticks(x,rotation=90)
plt.show()