Python Xlsxwriter 简明教程

Python XlsxWriter - Bar Chart

条形图类似于柱形图,不同之处在于数据用成比例的水平条表示,而不是垂直列。要生成条形图,方法 add_chart() 的类型参数必须设置为“bar”。

chart1 = workbook.add_chart({'type': 'bar'})

条形图如下所示 −

bar chart1

条形图有两个子类型,分别是堆叠和 percent_stacked 。在堆叠图中,某个分类的不同颜色的条形图一个接一个地放置。在 percent_stacked 图中,每个条形图的长度显示了其在每个分类的总值中的百分比。

chart1 = workbook.add_chart({
   'type': 'bar',
   'subtype': 'percent_stacked'
})

Example

生成百分比堆叠条形图的程序如下所示:

import xlsxwriter

wb = xlsxwriter.Workbook('hello.xlsx')
worksheet = wb.add_worksheet()
chart1 = wb.add_chart({'type': 'bar', 'subtype': 'percent_stacked'})

# Add the worksheet data that the charts will refer to.
headings = ['Name', 'Phy', 'Maths']
data = [
   ["Jay", 30, 60],
   ["Mohan", 40, 50],
   ["Veeru", 60, 70],
]

worksheet.write_row(0,0, headings)
worksheet.write_row(1,0, data[0])
worksheet.write_row(2,0, data[1])
worksheet.write_row(3,0, data[2])

chart1.add_series({
   'name': '=Sheet1!$B$1',
   'categories': '=Sheet1!$A$2:$A$4',
   'values': '=Sheet1!$B$2:$B$4',
})

chart1.add_series({
   'name': ['Sheet1', 0, 2],
   'categories': ['Sheet1', 1, 0, 3, 0],
   'values': ['Sheet1', 1, 2, 3, 2],
})
chart1.set_title ({'name': 'Marklist', 'name_font':
   {'name':'Times New Roman', 'size':24}})

chart1.set_x_axis({'name': 'Students', 'name_font':
   {'name':'Arial', 'size':16, 'bold':True}, })

chart1.set_y_axis({'name': 'Marks','name_font':
   {'name':'Arial', 'size':16, 'bold':True},
   'num_font':{'name':'Arial', 'italic':True}})

chart1.set_legend({'position':'bottom', 'font':
   {'name':'calibri','size': 9, 'bold': True}})

worksheet.insert_chart('B7', chart1)

wb.close()

Output

输出文件将如下所示:

bar chart2