python中繪製柱形圖、餅形圖等

最近因工作原因,使用python的繪圖功能,繪製生產的直通率數據,貼上代碼,便於以後需要時摘用
1.選擇報表所在路徑:
def ReportLocationpushButtonClick(self):
global ReportFileName
ReportFileName, ok = QFileDialog.getOpenFileName(self, “open file”, “./”, “csv file (*.csv .)”) # “/“代表當前目錄的根目錄
self.ReportLocationtextEdit.setText(str(ReportFileName))
ReportFileName = ReportFileName.replace(”\r”, r"\r").replace(’\n’, r’\n’)#防止轉義
2.讀取報表中的關鍵信息並繪製柱形圖
def pBar(self):
data = pd.read_excel(ReportFileName, names=[‘model’, ‘PO’,“Retest”])
df1 = data.groupby(‘model’)[‘PO’].sum().to_frame().reset_index()
self.graph.axes.set_ylim(0, 1800000)
self.graph.axes.set_yticks([0,600000,1200000,1800000])
rects = self.graph.axes.bar(range(len(df1.model)), df1.PO, color=‘rgby’)
self.graph.axes.set_xticks(np.arange(len(df1.model)))
self.graph.axes.set_xticklabels(df1.model,rotation=-70,fontsize=8)
self.graph.axes.grid(True)
for rect in rects:
height = rect.get_height()
self.graph.axes.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha=‘center’, va=‘bottom’, fontsize=10,
rotation=60)
3.讀取報表信息並繪製餅形圖
def pPie(self):
data = pd.read_excel(ReportFileName, names=[‘model’, ‘PO’, “Retest”])
df1 = data.groupby(‘model’)[‘PO’].sum().to_frame().reset_index()
explode = [x * 0.03 for x in range(len(df1.PO))]
self.graph.axes1.pie(df1.PO, explode, df1.model, autopct=’%3.1f %%’, labeldistance=1.1)
4.調用自定義繪製函數並顯示在窗體中
def pushButton_MatplotlibClick(self):
self.graph = MyFigure(12,6)
self.pBar()
self.pPie()
self.widget_Matplotlib.addWidget(self.graph, 0, 0)
5.自定義MyFigure類
class MyFigure(FigureCanvas):
def init(self,width=12, height=6):
self.fig = Figure(figsize=(width, height),facecolor= ‘y’)#第一步:創建一個Figure
super(MyFigure,self).init(self.fig) #此句必不可少,否則不能顯示圖形
#self.axes = self.fig.add_subplot(211)#縱向顯示兩個圖形
#self.axes1=self.fig.add_subplot(212)
self.axes = self.fig.add_subplot(121)#向顯示兩個圖形
self.axes1=self.fig.add_subplot(122)
6.按鈕鏈接
self.pushButton_Matplotlib.clicked.connect(self.pushButton_MatplotlibClick)
在這裏插入圖片描述
曲線圖
import matplotlib.pyplot as plt
import math
import numpy as np
import pandas as pd
da
ta = pd.read_excel(r’./data/fund_data_matplotlib.csv’, names=[‘name’, ‘ID’, ‘Value’])
data.Value1=(data.Value.astype(np.int))
plt.figure(figsize=(12, 6.5),facecolor= ‘y’)#畫布大小
plt.xticks(rotation=45)
plt.ylabel(“Value”) #X軸標籤
plt.xlabel(“Company Name”) #X軸標籤
plt.plot(data.ID, data.Value1, color=‘y’, linewidth=3)
for x, y in zip(data.ID,data.Value1):
plt.text(x, y, str(y), ha=‘center’, va=‘bottom’, fontsize=15 )
plt.savefig(‘aa.png’)
plt.grid()
plt.show()
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章