新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python中Excel圖表的繪制
1、餅圖將數(shù)據(jù)畫成圓形切片,每個(gè)切片代表整個(gè)百分比。

切片按順時(shí)針方向畫,圓頂0°。
# 繪制餅圖
import openpyxl
from openpyxl.chart import PieChart, Reference, BarChart, BubbleChart, ScatterChart # Reference:圖標(biāo)所用信息
from openpyxl.chart import Series
# 準(zhǔn)備數(shù)據(jù)
rows = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40]
]
# 將數(shù)據(jù)寫入excel
# 創(chuàng)建工作簿
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Pie Charts'
for row in rows:
ws.append(row)
# 繪制餅圖
pie_chart = PieChart()
# 設(shè)置標(biāo)題
pie_chart.title = 'Pie sold by category'
# 進(jìn)行分類
category = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=2, max_row=5) # 數(shù)據(jù)所在第2列
# 需要先添加數(shù)據(jù)再設(shè)置種類介紹
# 添加數(shù)據(jù)
pie_chart.add_data(data)
# 設(shè)置所分類別
pie_chart.set_categories(category)
# 在excel添加餅圖
ws.add_chart(pie_chart, 'D1') # 在D1位置繪制餅圖
# 保存
wb.save('char_excel_text.xlsx')
2、在條形圖中,值被繪制成水平條或垂直列。可以通過type屬性設(shè)置。
import openpyxl
from openpyxl.chart import PieChart, Reference, BarChart, BubbleChart, ScatterChart # Reference:圖標(biāo)所用信息
from openpyxl.chart import Series
# 繪制柱狀圖
# 創(chuàng)建工作表
ws = wb.create_sheet('Bar Chart')
# 準(zhǔn)備數(shù)據(jù)
rows = [
('Number', 'Batch1', 'Batch2'),
(2, 10, 30),
(3, 40, 60),
(4, 50, 70),
(5, 20, 10),
(6, 10, 40),
(7, 50, 30),
]
# 添加數(shù)據(jù)
for row in rows:
ws.append(row)
# 繪制柱狀圖
bar_chart = BarChart()
bar_chart.type = 'col' # col垂直、水平柱狀圖 bar
bar_chart.title = 'Bar Chart'
bar_chart.style = 10 # 設(shè)置顏色,10的對(duì)比度最強(qiáng),紅色與藍(lán)色
# 設(shè)置橫軸縱軸標(biāo)題
bar_chart.x_axis.title = 'Sample length(mm)'
bar_chart.y_axis.title = 'Test number'
# 設(shè)置分類
category = Reference(ws, min_col=1, min_row=2, max_row=7)
# 獲取數(shù)據(jù)
data = Reference(ws, min_col=2, max_col=3, min_row=1, max_row=7)
# 柱狀圖對(duì)象添加數(shù)據(jù)
bar_chart.add_data(data, titles_from_data=True) # titles_from_data=True:根據(jù)來源設(shè)置數(shù)據(jù)標(biāo)題
# 設(shè)置分類
bar_chart.set_categories(category)
# 工作頁(yè)繪制柱狀圖,并指定位置
ws.add_chart(bar_chart, 'E1')
# 保存
wb.save('char_excel_text.xlsx')
以上就是python中Excel圖表的繪制,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
本文名稱:創(chuàng)新互聯(lián)Python教程:python中Excel圖表的繪制
瀏覽地址:http://fisionsoft.com.cn/article/cohdcoo.html


咨詢
建站咨詢
