Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何避免Ytick或Xtick被损坏_Python_Matplotlib - Fatal编程技术网

Python 如何避免Ytick或Xtick被损坏

Python 如何避免Ytick或Xtick被损坏,python,matplotlib,Python,Matplotlib,我在matplotlib中设置XTick和Ytick时遇到问题,我想根据日期和价格(如BTC价格)绘制一个线图 我每30分钟更新一次价格,所以我想根据我拥有的每一个价格绘制一个绘图,但在xticks中只显示4-5个价格,在yticks中只显示一次日期(对不起,我的英语不好,我无法更好地解释) 因此,我将在这里向您展示: 我想要这样的价格(yticks): 和日期(XTICK),如: 但我的输出被破坏了: 完整代码: class PriceChangePlots: def __i

我在matplotlib中设置XTick和Ytick时遇到问题,我想根据日期和价格(如BTC价格)绘制一个线图 我每30分钟更新一次价格,所以我想根据我拥有的每一个价格绘制一个绘图,但在xticks中只显示4-5个价格,在yticks中只显示一次日期(对不起,我的英语不好,我无法更好地解释)

因此,我将在这里向您展示:

我想要这样的价格(yticks):

和日期(XTICK),如:

但我的输出被破坏了:

完整代码:


class PriceChangePlots:

    def __init__(self, session: Session, for_cars: bool):
        self.for_cars = for_cars
        self.media_path = 'media/'
        self.font_nazanin = fm.FontProperties(fname=self.media_path + 'fonts/BNAZANIN.TTF', size=14)
        self.font_yekan = fm.FontProperties(fname=self.media_path + 'fonts/BYekan+.ttf', size=14)
        self.DB = session
        self.chart: Charts = self.DB.query(Charts)
        self.cars = self.DB.query(Prices)

    def get_model_data(self, model_code):
        cars = self.cars

        # get model data from database
        models = cars.with_entities(
            Prices.datetime, Prices.price).filter(
            Prices.datetime > datetime.now() - timedelta(weeks=1)).filter_by(
            model_code=model_code).all()

        # convert datetime to persian dates
        JD = jdatetime.date.fromgregorian  # make an object of datetime converter
        models = list(
            map(
                lambda details:
                (JD(date=details[0].date()), details[1]),  # tuple of details
                #          ^^^ DATE          ^^^ PRICE
                models
            ))

        # make a dictionary to avoid repeat days
        # models = _remove_duplicates(models)
        # data = dict(models)
        return models

    @staticmethod
    def fa(persian_text):
        reshaped_text = arabic_reshaper.reshape(persian_text)
        farsi_text = get_display(reshaped_text)
        return farsi_text

    def line(self, model_code):
        cars = self.cars
        for_cars = self.for_cars

        model: Prices = cars.filter_by(model_code=model_code).first()
        fa = self.fa
        data = self.get_model_data(model_code)
        plt.style.use('default')

        dates = list(map(lambda x: x[0], data))  # dates
        prices = list(map(lambda x: x[1], data))  # prices

        average = np.average(prices)  # average of car price in last 2 weeks
        average = round(average, 2)  # round it with 2 decimals

        # if average is greater than 1M
        if average > 10 ** 6:
            avg_label = round(average / 10 ** 6, 2)
        else:
            avg_label = average

        # check if average have decimals or not
        if avg_label.is_integer():
            avg_label = int(avg_label)

        # average line
        if average > 10 ** 6:
            avg_label = f'{fa("میانگین")}={avg_label}M'
        else:
            avg_label = f'{fa("میانگین")}={avg_label}'

        fig: Figure
        ax: Axes
        fig, ax = plt.subplots()

        dates_array = np.arange(len(dates))

        # prices axe
        a: Line2D = ax.plot(dates_array, prices, linewidth=3)

        # print(type(b))

        ax.plot(dates_array, [average] * len(prices), linestyle='-.', linewidth=2,
                color='#6495ed', label=avg_label)

        ax.fill_between(dates_array, prices, average,
                        where=(prices > average), color='red',
                        alpha=0.2, interpolate=True, label=fa('بزرگتر از میانگین'))

        ax.fill_between(dates_array, prices, average,
                        where=(prices < average), color='green',
                        alpha=0.2, interpolate=True, label=fa('کوچکتر از میانگین'))

        if for_cars:
            title = fa(f"تغییرات قیمت %s %s" % (model.brand, model.model_name))
        else:
            title = fa(f"تغییرات قیمت %s" % model.model_name)

        plt.title(title, fontproperties=self.font_yekan, size=20)

        ax.grid(color='k', linewidth=.5, linestyle=':', axis='y')

        # shorten prices ( price / 1M )
        y_ticks = []
        for price in prices:
            if price > 10 ** 6:
                price = round(price / 10 ** 6, 2)

                if price.is_integer():  # if price have no decimals
                    price = int(price)
                    price = s(price)
                price = f'{price}M'

            else:
                price = float(round(price, 2))
                if price.is_integer():  # if price have no decimals
                    price = int(price)
                    price = s(price)

            y_ticks.append(price)

        # _: Line2D
        # y_data = a[0].get_ydata()

        # plt.yticks(y_data, y_ticks)
        plt.xticks(dates_array, dates, rotation=45)

        fig.text(0.5, 0.55, fa("قیمت روزانه خودرو:\nt.me/CPricesBot"),  # 't.me/CPricesBot',
                 fontsize=40, color='gray', fontproperties=self.font_yekan,
                 ha='center', va='center', alpha=0.30, size=25)

        legend: Legend = ax.legend()

        # change legend font
        text: Text
        for text in legend.texts:
            text.set_fontproperties(self.font_yekan)
            text.set_fontsize(10)

        fig.tight_layout(pad=2)

        # fig.savefig(self.media_path + 'plots/price_change_plots/' + model_code + '.png')
        fig.show()

        plt.close()

类别价格变化图:
定义初始化(self,session:session,for_cars:bool):
self.for_cars=for_cars
self.media\u路径='media/'
self.font\u-nazanin=fm.FontProperties(fname=self.media\u path+'font/BNAZANIN.TTF',size=14)
self.font\u yekan=fm.FontProperties(fname=self.media\u path+'font/BYekan+.ttf',size=14)
self.DB=会话
self.chart:Charts=self.DB.query(图表)
self.cars=self.DB.query(价格)
def获取模型数据(自身、模型代码):
汽车
#从数据库中获取模型数据
模型=汽车。带有实体(
Prices.datetime,Prices.price).过滤器(
Prices.datetime>datetime.now()-timedelta(weeks=1)).filter\u by(
型号代码=型号代码)。全部()
#将datetime转换为波斯日期
JD=jdatetime.date.fromgregorian#将datetime转换器作为对象
型号=列表(
地图(
lambda详细信息:
(JD(日期=详细信息[0]。日期()),详细信息[1]),#详细信息元组
#^^^^日期^^^价格
模型
))
#编一本字典以避免重复
#模型=\u删除\u重复项(模型)
#数据=dict(型号)
返回模型
@静力学方法
def fa(波斯语文本):
重塑文本=阿拉伯语重塑器。重塑(波斯语文本)
波斯语文本=获取显示(重塑文本)
返回波斯语文本
def管路(自身,型号代码):
汽车
对于车=自我。对于车
型号:价格=汽车。筛选依据(型号代码=型号代码)。第一()
fa=self.fa
数据=自身。获取模型数据(模型代码)
plt.style.use('default')
日期=列表(映射(λx:x[0],数据))#日期
价格=列表(地图(λx:x[1],数据))#价格
平均值=np.平均值(价格)#过去两周内汽车价格的平均值
平均值=四舍五入(平均值,2)#用2位小数将其四舍五入
#如果平均值大于1M
如果平均值>10**6:
平均标签=圆形(平均值/10**6,2)
其他:
平均标签=平均值
#检查平均值是否有小数
如果avg_label.is_integer():
平均标签=int(平均标签)
#平均线
如果平均值>10**6:
avg_label=f'{fa(“avgیاانگین”)}={avg_label}M'
其他:
avg_label=f'{fa(avgیlabel}}
图:图
斧头:斧头
图,ax=plt.子批次()
日期数组=np.arange(len(日期))
#降价
a:Line2D=ax.plot(日期、价格、线宽=3)
#印刷品(b类)
ax.绘图(日期数组,[平均值]*长度(价格),线型='-',线宽=2,
颜色='#6495ed',标签=平均标签)
ax.填充时间间隔(日期、价格、平均值、,
其中=(价格>平均值),颜色=红色,
alpha=0.2,插值=True,标签=fa
ax.填充时间间隔(日期、价格、平均值、,
式中=(价格<平均值),颜色=(绿色),
alpha=0.2,插值=True,标签=fa
如果适用于汽车:
title=fa(f“品牌、型号、型号、型号名称))
其他:
title=fa(f“تغییتقتمت%s”%model.model_name)
plt.title(title,fontproperties=self.font_yekan,size=20)
ax.grid(color='k',linewidth='.5,linestyle='':',axis='y')
#缩短价格(价格/1M)
y_ticks=[]
价格中的价格:
如果价格>10**6:
价格=整数(价格/10*6,2)
if price.is_integer():#if price没有小数
价格=整数(价格)
价格=s(价格)
price=f'{price}M'
其他:
价格=浮动(四舍五入(价格,2))
if price.is_integer():#if price没有小数
价格=整数(价格)
价格=s(价格)
y_ticks.append(价格)
#_u2;:Line2D
#y_data=a[0]。获取_ydata()
#plt.yticks(y_数据,y_刻度)
plt.xticks(日期数组,日期,旋转=45)
图文本(0.5,0.55,fa(“t.me/CPricesBot”),“t.me/CPricesBot”,
fontsize=40,color='gray',fontproperties=self.font\u yekan,
ha='center',va='center',alpha=0.30,尺寸=25)
图例:legend=ax.legend()
#更改图例字体
文本:文本
对于legend.text中的文本:
text.set_fontproperties(self.font_yekan)
文本。设置字体大小(10)
图2紧固件布局(焊盘=2)
#图savefig(self.media_path+‘plots/price_change_plots/'+model_code+’.png')
图2(图3)
plt.close()

确保不打印字符串,而是打印真实日期。有帮助吗?