问题在于,在生成输出时,Y轴与绘图之间没有空间。我已经尝试过对齐和边距,但没有任何影响。
关于我可以尝试获得相同结果的任何指针,无论使用哪种机器。我正在使用Jupyter Notebook
#FINAL CODE TILL 26 JULY 2019
import glob
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from pandas import ExcelWriter
import pickle
import xlrd
import os
import re
#Change directory to Input folder
#os.chdir("C:\\Users\\600009336\\Desktop\\Report\\Input\\Closed\\Deep31July")
#
os.chdir("C:\\Users\\600009336\\Desktop\\Report_RSE\\Input\\Closed_Faults")
#
#os.chdir("C:\\Users\\600009336\\Desktop\\Report_RSE\\Input\\Closed_Faults")
#
#os.chdir("C:\\Users\\600009336\\Desktop\\Report_RSE\\Input\\Closed_Faults")
#Get filenames from the directory
for f in glob.glob("*.xlsx"):
print(f)
#Print the filename
Raw_Close2=pd.read_excel(f,encoding='cp1252')
workbook = xlrd.open_workbook(f)
worksheet = workbook.sheet_by_name('Sheet1')
Contract_Name=worksheet.cell(1,2)
print(Contract_Name)
Contract_Name2=str(Contract_Name)
Contract_Name3=re.findall(r'''(?<=')\s*[^']+?\s*(?=')''',Contract_Name2)
Contract_Name3=str(Contract_Name3)
Contract_Name4=Contract_Name3.strip('\[ ]')
Contract_Name4=Contract_Name4.strip('\'')
#Get the contract name for end fliename
#
output_img="C:\\Users\\600009336\\Desktop\\Report_RSE\\Output\\Closed_Faults\\(%s).png" % Contract_Name4
output_txt="C:\\Users\\600009336\\Desktop\\Report_RSE\\Output\\Closed_Faults\\(%s).txt" % Contract_Name4
Raw_Close=pd.read_excel(f,encoding='cp1252',skiprows=4)
#Read the dataset for actual data processing
#print(Raw_Close.head(1))
#Get the max month value
Max_date=Raw_Close['Closed On'].max()
Max_Month=Max_date.strftime('%B')
#Dataset reporting only for remotely managed True faults
Raw_Close=Raw_Close[Raw_Close['Is Remotely Managed (Asset)']==True]
#--Resolution Time calculation
Raw_Close['Resolution_Time']=Raw_Close['Closed On']-Raw_Close['Created on']
#--Change into days
Raw_Close['Resolution_Time2']=np.ceil((Raw_Close['Resolution_Time']/ np.timedelta64(1, 'D')).astype(int))
#--Calculate the aggrgates
Raw_Close_pt=Raw_Close.groupby(['Category','Control System (Control Gear)']).agg({'ID (Fault)':'nunique','Resolution_Time2':'mean'}).reset_index()
#--Round to next highest number
Raw_Close_pt['Resolution_Time2']=np.ceil(Raw_Close_pt['Resolution_Time2'])
#--Function to change and the rename per Marcomm
def rename(Raw_Close_pt):
if(Raw_Close_pt['Control System (Control Gear)']=='Direct Communication'):return '# Light Points Client'
elif(Raw_Close_pt['Control System (Control Gear)']=='Philips Starsense Wireless'):return '# Light Points RF'
elif(Raw_Close_pt['Control System (Control Gear)']=='Philips Starsense Powerline'):return '# Light Points Powerline'
#--Apply the function on the dataframe
Raw_Close_pt['Control_System']=Raw_Close_pt.apply(rename,axis=1)
#Rename the column names
Raw_Close_pt=Raw_Close_pt.rename(columns={"ID (Fault)":"Count_CntrlSyst","Resolution_Time2":"Resol_Time"})
#--Change format to create Bar graph
Raw_Close_pt2=Raw_Close_pt.pivot(index='Category',columns='Control_System',values='Count_CntrlSyst')
Raw_Close_pt2.reset_index()
#--Color Coding Marcomm
colors = ["#C0C0C0", "#767171","#a5a5a5"]
#colors=["#add8e6","#e6bbad","#ade6d8"]
from datetime import datetime
This_Month=datetime.now().strftime('%B')
#print(Raw_Close_pt2.head(7))
#--Bar Chart
p1=Raw_Close_pt2.plot(kind='bar',width=0.3,stacked=True,color=colors,figsize=(15, 9),legend=None,zorder=1)
#p1=Raw_Close_pt2.plot(kind='bar',width=0.3,stacked=True,figsize=(15, 9),legend=None,zorder=0.1)
p1.set_ylabel('Light Points',fontsize=12)
p1.set_xlabel('Category',fontsize=12)
p1.tick_params(labelsize=13)
p1.margins(0.90,0)
p1.grid(False)
#p1.set_ylabel('Days of Resolution')
Raw_Close_pt2_1=Raw_Close.groupby(['Category']).agg({'Resolution_Time2':'mean'}).reset_index()
#--Round to next highest number
Raw_Close_pt2_1['Resolution_Time2']=np.ceil(Raw_Close_pt2_1['Resolution_Time2'])
Raw_Close_pt2_1=Raw_Close_pt2_1.rename(columns={"Resolution_Time2":"Average_Resolution_Time"})
#Raw_Close_pt_1=Raw_Close_pt2_1[['Category','Resol_Time']]
#p1.set_ylabel('Days of Resolution')
Raw_Close_pt_1=Raw_Close_pt2_1[['Category','Average_Resolution_Time']]
#print(Raw_Close_pt_1.head(7))
#Raw_Close_pt_1=Raw_Close_pt[['Category','Resol_Time']]
p2=Raw_Close_pt_1['Average_Resolution_Time'].plot(secondary_y=True,figsize=(15, 9),color='#FF375F',marker='o',zorder=50)
#p2.legend(10)
p2.set_ylabel('Days of Resolution',fontsize=12)
p2.tick_params(colors='#FF375F',labelsize=13)
for i,j in Raw_Close_pt_1.Average_Resolution_Time.items():
p2.annotate(str(j), xy=(i, j),color='#FF375F', horizontalalignment='right', verticalalignment='top',fontsize=13)
p1.legend(loc="upper left",bbox_to_anchor=(0.5, 1.16))
p2.legend(loc="upper right",bbox_to_anchor=(0.5, 1.16))
print(output_img)
#plt.title(f"Faults resolved in {Max_Month} 2019",fontsize=15)
plt.grid(which='both',color='#D9D9D9', linestyle='-',alpha=0.3,zorder=1)
#plt.grid(which='both', linestyle='-',alpha=0.8,zorder=3)
plt.rcParams['xtick.labelsize']=12
plt.rc('axes', axisbelow=True)
plt.savefig(output_img)
plt.show()
#Resolution Time text
from datetime import datetime
Avg_Resol_Time=round(Raw_Close["Resolution_Time2"].mean(),1)
print(Avg_Resol_Time)
#This_Month=datetime.now().strftime('%B')
Resol_Time_Txt=f"Faults resolved in Quarter 3 (average resolution time: {Avg_Resol_Time} "+""+"days"+")"
f=open(output_txt,"w")
f.write(Resol_Time_Txt)
f.close()
print("Done All")
预期结果是一个组合图,其中绘图结果和Y轴之间有间隔。