第一節:Pygal下載和安裝入門
安裝pygal安裝pygal包跟安裝其他Python包基本相似,同樣可以使用pip來安裝啟動命令列視窗,輸入命令:pip install pygal安裝成功後,可透過pydoc來檢視文件,輸入命令:python -m pydoc -p 8899pygal入門用法建立pygal資料圖物件,不同的資料圖使用不同的類呼叫資料圖物件的add()方法新增資料呼叫config物件的屬性配置資料圖呼叫資料圖的render_to_xxx()方法將資料圖渲染到指定的輸出節點import pygalyear_data = [str(i) for i in range(2011,2020)]java_data = [17.89, 18.29, 20.45, 19.28, 20.35, 21.23, 19.98, 20.24, 19.56]python_data = [4.89, 4.29, 4.45, 5.28, 5.35, 6.23, 6.98, 7.24, 9.56]# 建立圖bar = pygal.Bar()bar.title = 'java與Python歷年的市場份額'# 新增資料bar.add('java語言市場份額', java_data)bar.add('Python語言市場份額', python_data)# 配置資料'''配置資訊: x_labels:X軸座標 title:標題 x_title:設定X軸標題 y_title:設定Y軸標題'''bar.x_labels = year_databar.x_title = '年份'bar.y_title = '市場份額'# 輸出到圖片bar.render_to_file('language.svg')
config模組配置pygal圖該模組包含了BaseConfig CommonConfig Config SerieConfig等配置類import pygalyear_data = [str(i) for i in range(2011,2020)]java_data = [17.89, 18.29, 20.45, 19.28, 20.35, 21.23, 19.98, 20.24, 19.56]python_data = [4.89, 4.29, 4.45, 5.28, 5.35, 6.23, 6.98, 7.24, 9.56]# 建立圖bar = pygal.Bar()bar.title = 'java與Python歷年的市場份額'# 新增資料bar.add('java語言市場份額', java_data)bar.add('Python語言市場份額', python_data)# 配置資料bar.x_labels = year_databar.x_title = '年份'bar.y_title = '市場份額'# 設定X軸的標籤旋轉多少度bar.x_label_rotation = 45# 設定將圖例放在下面bar.legend_at_bottom = True# 設定四周的頁邊距,也可使用margin_bottom margin_top margin_right margin_left分別設定bar.margin = 35# 隱藏Y軸的網格線bar.show_y_guides = False# 顯示X軸的網格線bar.show_x_guides = True# 輸出到圖片bar.render_to_file('language.svg')
柱狀圖
折線圖
第二節:水平柱狀圖和水平折線圖
水平柱狀圖使用pygal.HorizontalBar類代表x_labels屬性用於設定Y軸的刻度值,而y_labels屬性才是配置X軸的刻度值水平折線圖水平折線圖使用pygal.HorizontalLine代表x_labels屬性用於設定Y軸的刻度值,而y_labels屬性才是配置X軸的刻度值import pygalyear_data = [str(i) for i in range(2011,2020)]java_data = [17.89, 18.29, 20.45, 19.28, 20.35, 21.23, 19.98, 20.24, 19.56]python_data = [4.89, 4.29, 4.45, 5.28, 5.35, 6.23, 6.98, 7.24, 9.56]'''pygal.Bar代表柱狀圖pygal.Line代表折線圖pygal.HorizontalBar代表水平柱狀圖pygal.HorizontalLine代表水平折線圖# bar = pygal.Bar()# bar = pygal.Line()# bar = pygal.HorizontalBar()'''# 建立圖bar = pygal.HorizontalLine()bar.title = 'java與Python歷年的市場份額'# 新增資料bar.add('java語言市場份額', java_data)bar.add('Python語言市場份額', python_data)# 配置資料'''# 折線圖的資料設定內容bar.x_labels = year_databar.x_title = '年份'bar.y_title = '市場份額(百分比)''''# 對於水平柱狀圖,x_labels 其實是設定Y軸的座標bar.x_labels = year_databar.y_title = '年份'bar.x_title = '市場份額(百分比)'# 設定X軸的標籤旋轉多少度bar.x_label_rotation = 45# 設定將圖例放在下面bar.legend_at_bottom = True# 設定四周的頁邊距,也可使用margin_bottom margin_top margin_right margin_left分別設定bar.margin = 35# 隱藏Y軸的網格線bar.show_y_guides = True# 顯示X軸的網格線bar.show_x_guides = True# 輸出到圖片bar.render_to_file('language.svg')
水平柱狀圖
水平折線圖
第三節:疊加柱狀圖
和疊加折線圖
疊加柱狀圖使用pygal.StackedBar代表疊加折線圖使用pygal.StackedLine代表水平疊加柱狀圖使用pygal.HorizontalStackedBar代表水平疊加折線圖使用pygal.HorizontalStackedLine代表import pygalimport randomyear_data = [str(i) for i in range(2011,2020)]banana_data = [random.randint(20, 40) * 1000 for i in range(1, 10)]apple_data = [random.randint(35, 60) * 1000 for i in range(1, 10)]# pygal.StackedBar代表疊加柱狀圖 pygal.StackedLine代表疊加折線圖# graph = pygal.StackedBar()graph = pygal.StackedLine()graph.title = '香蕉與蘋果歷年的銷量分析'# 新增資料graph.add('香蕉的歷年銷量', banana_data)graph.add('蘋果的歷年銷量', apple_data)# 配置資料graph.x_labels = year_datagraph.x_title = '年份'graph.y_title = '銷量(噸)'# 設定X軸的標籤旋轉多少度graph.x_label_rotation = 45# 設定將圖例放在下面graph.legend_at_bottom = True# 設定四周的頁邊距graph.margin = 35# 隱藏Y軸的網格線graph.show_y_guides = True# 顯示X軸的網格線graph.show_x_guides = True# 輸出到圖片graph.render_to_file('fruit.svg')
疊加柱狀圖
疊加折線圖
第四節:餅圖和點圖
餅圖餅圖用於各成員所佔的份額可支援傳統的餅圖、也可做成空心的餅圖、也可做成半圓餅圖等import pygal# 2018年8月程式語言的市場份額data = {'Java': 0.16881, 'C': 0.14996, 'C++': 0.07471, 'Python': 0.06992, 'VB.net': 0.04762, 'C#': 0.03541, 'PHP': 0.02925, 'JavaScript': 0.02411, 'SQL': 0.02316, 'Assembly languagage': 0.01409, '其他': 0.36326} # 建立餅圖 pygal.Pie()graph = pygal.Pie()for k in data.keys(): graph.add(k, data[k])graph.title = '2018年8月程式語言的市場份額'graph.legend_at_bottom = True# 空心餅圖graph.inner_radius = 0.8# 半圓餅圖graph.half_pie = Truegraph.reader_to_file('language.svg')
餅圖
環形餅圖
半圓餅圖
點圖點圖使用點的大小來表示數值的大小pygal使用pygal.Dot類代表點圖import pygalimport randomyear_data = [str(i) for i in range(2011,2020)]banana_data = [random.randint(20, 40) * 1000 for i in range(1, 10)]apple_data = [random.randint(35, 60) * 1000 for i in range(1, 10)]# pygal.Dot代表點圖graph = pygal.Dot()graph.title = '香蕉與蘋果歷年的銷量分析'# 新增資料graph.add('香蕉的歷年銷量', banana_data)graph.add('蘋果的歷年銷量', apple_data)# 配置資料graph.x_labels = year_datagraph.x_title = '年份'# 設定X軸的標籤旋轉多少度graph.x_label_rotation = 45# 設定將圖例放在下面graph.legend_at_bottom = True# 設定四周的頁邊距graph.margin = 35# 隱藏Y軸的網格線graph.show_y_guides = True# 顯示X軸的網格線graph.show_x_guides = True# 輸出到圖片graph.render_to_file('fruit.svg')
點圖
第五節:案例實操-使用Pygal分析天氣資料
下載、提取資料使用urllib.request向m.tianqi.com傳送請求,獲取該網站的響應再使用Python的re模組來解析伺服器響應,從中提取天氣資料import urllib.request, reimport datetimeimport pygaldef get_html(city, year, month): url = 'https://m.tianqi.com/lishi/%s/%s%s.html' % (city, year, month) request = urllib.request.Requst(url) # 設定User-Agent頭,避免產生403錯誤 request.add_header('User-Agent', 'Mozilla/5.0') return urllib.request.urlopen(request).read().decode('UTF-8')# print(get_html('guangzhou', '2018', '01l'))dates, highs, lows = [], [], []city = 'guangzhou'year = '2018'month = ['%02d' % i for i in range(1, 13)]# 定義一個開始的日期,用於判斷資料是否缺少某一天prev_day = datetime.datetime(2017, 12, 31)for month in months: # 下載網頁原始碼 html = get_html(city, year, month) # 將網頁原始碼的空格去掉 nospce_test = ''.join(html.split()) # 定義獲取全部天氣資料的div元素所對應的正則表示式 pattern = re.compile('<divclass="weatherbox">(.*?)</div><divclass="clearline1">') div_list = re.finall(pattern, nospce_test) # 定義包含每日天氣對應的dl元素所對應的正則表示式 pattern1 = re.compile('<dlclass="table_day15">(.*?)</dl>') dls = re.findall(pattern1, div_list[0]) # 再次遍歷dls去獲取每天的資料 for dl in dls: # 日期對應正則表示式 date_pattern = re.compile('<ddclass="date">(.*?)</dd>') date_dd = re.finall(date_pattern , dl) # 生成日期格式字串 d_str = year + "/" + date_dd[0][0:5] # 氣溫資訊對應的正則表示式 temp_pattern = re.compile('<ddclass="txt2">(.*?)</dd>') temp_dd = re.finall(temp_pattern ,dl) # 最低氣溫資訊對應的正則表示式 low_pattern = re.compile('^(.*?)~') low_li = re.finall(low_pattern , temp_dd[0]) # 最高氣溫資訊對應的正則表示式 high_pattern = re.compile('<b>(.*?)</b>') high_li = re.finall(high_pattern , temp_dd[0]) try: cur_day = datetime.datetime.strptime(d_str, '%Y/%m/%d') # 得到最低氣溫和最高氣溫 low = int(low_li[0]) high= int(high_li[0]) except ValueError: print('cur_day', '溫度資料有錯') else: # 資料清洗,判斷是否差某一天 diff = cur_day - prev_day # 如果兩個日期之間差值不是一天,說明資料丟失了 if diff != datetime.timedelta(days = 1): print('在%s之前丟失了%d天的資料' % (d_str, diff.days - 1)) dates.append(d_str) lows.append(low) highs.append(high) prev_day = cur_day# 建立圖bar = pygal.Line()bar.title = '廣州%s年的氣溫分析' % year# 新增資料bar.add('最低氣溫', lows)bar.add('最高氣溫', highs)# 配置資料bar.x_labels = datas# 設定X軸的主刻度bar.x_labels_major = dates[::30]# 設定不顯示X軸上的小刻度(避免密密麻麻的情況)bar.show_minor_x_labels = Falsebar.x_title = '日期'bar.y_title = '氣溫(攝氏度)'# 設定X軸的標籤旋轉多少度bar.x_label_rotation = 45# 設定將圖例放在下面bar.legend_at_bottom = True# 隱藏Y軸的網格線bar.show_y_guides = True# 顯示X軸的網格線bar.show_x_guides = False# 輸出到圖片bar.render_to_file('temp.svg')
天氣分析圖
最新評論