簡體   English   中英

繪圖 X 軸上的日期過度擁擠:Python

[英]Dates Overcrowding on X-Axis of Plot :Python

我目前在 x 軸上重疊顯示的 x 標簽存在問題,導致標簽難以辨認。

我已經嘗試過的:

1) 軸已將刻度旋轉到 60 度,但有些圖仍然重疊

2) Locator_params 已經試過了,但是會拋出“AttributeError: 'List' object has no attribute 'locator_params'”的錯誤

3)使用mdates訪問年月定位器也沒有成功。 以下是我嘗試過的示例代碼; 從源頭; Matplotlib 日期操作,以便每 12 個月顯示一次年份刻度

        years = mdates.YearLocator()
        months = mdates.MonthLocator()
        monthsFmt = mdates.DateFormatter('%b-%y')
        yearsformat=mdates.DateFormatter('\n\n%Y')
        ###
        ax.xaxis.set_minor_locator(months)
        ax.xaxis.set_minor_formatter(monthsFmt)
        ####
        plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)
        ax.xaxis.set_major_formatter(years)
        ax.xaxis.set_major_formatter(yearsformat)

我相信我可能誤解了如何使用 locator_params 和 mdates。

筆記:

1) 我正在使用一個循環來制作 ~200 個具有不同 xticks 數量的圖,一些具有 400+,其他只有 15。因此,我想嘗試將最大刻度數設置為 ~30-40,如果可能的。 但是,我也願意接受其他想法和建議。

代碼段:

 def plotme(df,string,ref):
        for i in range(0,len(df.columns)):
             #Scatter plot the active ingredient data. 
             plotdf=df.iloc[:,i].dropna()
             #Store length of df
             length=len(plotdf.index) 



    #Decide on length to cutoff. If index is shorter then 10 datapoints, 
        exclude it
        if length > 10:
            #Dataframes setup for Statistics Fucntion
            statss=pd.to_numeric(df.iloc[:,i],errors='coerce')
            #Last value in the dataframe, aka the most recent
            lastvalue=statss[-1]
            lastvalue=round(lastvalue,2)
            #String Manipulations
            #Possibly make a function for this
            temp5=str(ref[i])
            table = str.maketrans(dict.fromkeys("([)]'"))
            temp5=temp5.translate(table)
            temp6=temp5.split(',')

            #The Iterative Dict split up for accessing
            low=float(temp6[1])
            low=round(low,2)
            high=float(temp6[2])
            high=round(high,2)
            active=str(temp6[0])
            uom=str(temp6[3])
            usl=' USL ' + str(high)
            lsl=' LSL ' + str(low)

            #Call to fucntion for Statistical analysis; a list is returned
            #List order; 0==Cp, 1==Cpk, 2==Mean, 3==Standard          
            stat=statistics(statss,high,low)
            mean=stat[2]
            standard=stat[3]
            cp=stat[0]
            cpk=stat[1]
            meanstr=str(mean) + ' $\mu$'
            title=string + ' ' + active
            subtitle='The Cp is ' +str(cp) + ' while the CpK is ' +str(cpk)
            ylabel=active + '  (' + uom +')'
            plt.figure(0)
            #Index is date logged currently, change when index is greater than 100, as overcrowding occurs
            ax,=plt.plot(plotdf.index,plotdf, marker='o', linewidth=1, markersize=3)
            #ax.locator_params(nbins=4)
            #Changing Plot Axis and adding the reference line
            plt.title(title)
            plt.ylabel(ylabel)
            plt.xlabel('Date Logged',fontsize=8)
            plt.rc('xtick', labelsize=7)
            plt.plot([0,length],[low,low],'r-',lw=3)
            plt.plot([0,length],[high,high],'r-',lw=3)
            plt.xlim(0,length)
            plt.xticks(rotation=60)
            #plt.xticks(plt.xticks()[0][1::2], 
            #plt.xticks()[1][1::2])
            #plt.gca().xaxis.set_major_locator(mdates.DayLocator((1,15)))
            #plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%d %b %Y"))
            ax.locator_params(axis='x',nbins=40)

            plt.plot([0,length],[mean,mean],'g',lw=2,label='$\mu$')
            #Add the USL and LSL
            #Possibly use Hline subclass instead for efficiency(?)
            plt.text((length+0.5),high,usl,fontsize=7,color='red')
            plt.text((length+0.5),low,lsl,fontsize=7,color='red')
            plt.text((length+0.5),mean,meanstr,fontsize=7,color='green')
            #For loop to plot the sigma lines
            for i in range(1,5):
                minsig=mean-i*standard
                adsig=mean+i*standard
                cond1=math.isnan(adsig)
                cond2=math.isnan(minsig)
               ####Figure out later####
                # if (minsig or adsig) 
                ##Some of the minsig and adsig calculations are nan resulting in an error converting nan to an integer.
                if ((cond1==False) and (cond2==False)):
                    plt.plot([0,length],[minsig,minsig],'k--',lw=1,label='+' + str(i)+' ' + '$\sigma$')
                    plt.plot([0,length],[adsig,adsig],'k--',lw=1,label='-' + str(i)+ ' ' + '$\sigma$')
                    plt.text((length+0.1),minsig,'-' + str(i)+' ' + '$\sigma$',fontsize=6)
                    plt.text((length+0.1),adsig,'+' + str(i)+' ' + '$\sigma$',fontsize=6)
            #Save the plots as the name of the title and delete the white space in order to maximize viewability
            plt.savefig(title + '.png', bbox_inches='tight',format='png',dpi=800)   
            plt.show()    
            plt.figure(1)
            plt.rc('xtick', labelsize=8)
            sns.distplot(a=plotdf,bins=20,hist_kws=dict(edgecolor='k',linewidth=2))
            plt.axvline(low, color='r', linestyle='solid', linewidth=2)
            plt.axvline(mean, color='g', linestyle='dashed', linewidth=2)
            plt.axvline(high, color='r', linestyle='solid', linewidth=2)

            plt.xlabel(ylabel)
            plt.title(title + '\n' + subtitle)
            plt.savefig(title + ' Normal' +'.png',bbox_inches='tight',format='png',dpi=800)

問題示例:具有重疊 x 軸標簽的問題圖像

間隔良好的理想情況示例

提前感謝大家的任何幫助。

如果旋轉后仍有一些重疊,也許如果您使用plt.tight_layout()會更好。 所以試試這個

plt.xlabel(ylabel)
plt.title(title + '\n' + subtitle)
plt.tight_layout()
plt.savefig(title + ' Normal' +'.png',bbox_inches='tight',format='png',dpi=800)

是不是刻度標簽太大的問題? 您可以使用 set_tick_params 中的“labelsize”將大小調整為更小

ax.xaxis.set_tick_params(rotation=30, labelsize=3)

來自 matplotlib 教程

或者,這就是我在自己的代碼中使用的:

plt.gca().xaxis.set_tick_params(rotation = 30, labelsize=3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM