2015-06-19 121 views
1

我有了下面的方案xlsxwriter結合圖表類型

A B   C   D 

    ID Reading 1 Reading 2 Avg Reading 1 
    0 4.2   6.7   3.98 
    1 4.4   8.8 
    2 4.5   9 
    3 5.6   4 
    4 1.2   4.5 

我能畫一個直方圖讀數1和2,閱讀

chart_1 = workbook.add_chart({'type': 'column'}) 
chart_1.add_series({ 
     'name':  '=Sheet1!$B$1', 
     'categories': '=Sheet1!$A$2:$A$4, 
     'values':  '=Sheet1!$B$2:$B$4, 
    }) 

我想覆蓋的Excel圖表橫跨直方圖表示平均讀數1的線。我如何使用python和xlsxwriter做到這一點?

回答

0

Excel和XlsxWriter在圖表中支持Trendlines。然而,只有一個移動平均期權,而不是一個固定的平均期權(考慮到趨勢的原因,這是有道理的)。

您在Excel中做這種事的常用方法是在直方圖頂部添加一個包含平均值的折線圖。

這是基於你的數據一個小工作示例:

from xlsxwriter.workbook import Workbook 

workbook = Workbook('chart_combined.xlsx') 
worksheet = workbook.add_worksheet() 

# Add a format for the headings. 
bold = workbook.add_format({'bold': True}) 

# Make the columns wider. 
worksheet.set_column('B:C', 12) 

# Add the worksheet data that the charts will refer to. 
headings = ['ID', ' Reading 1', ' Avg Reading 1'] 
data = [ 
    [0, 1, 2, 3, 4], 
    [4.2, 4.4, 4.5, 5.6, 1.2], 
    [3.98, 3.98, 3.98, 3.98, 3.98], 
] 
worksheet.write_row('A1', headings, bold) 
worksheet.write_column('A2', data[0]) 
worksheet.write_column('B2', data[1]) 
worksheet.write_column('C2', data[2]) 

# Create a combined column and line chart that share the same X and Y axes. 

# First create a column chart. This will use this as the primary chart. 
column_chart = workbook.add_chart({'type': 'column'}) 

# Configure the data series for the primary chart. 
column_chart.add_series({ 
    'name':  '=Sheet1!$B$1', 
    'categories': '=Sheet1!$A$2:$A$6', 
    'values':  '=Sheet1!$B$2:$B$6', 
}) 

# Create a line chart. This will use this as the secondary chart. 
line_chart = workbook.add_chart({'type': 'line'}) 

# Configure the data series for the secondary chart. 
line_chart.add_series({ 
    'name':  '=Sheet1!$C$1', 
    'categories': '=Sheet1!$A$2:$A$6', 
    'values':  '=Sheet1!$C$2:$C$6', 
}) 

# Combine the charts. 
column_chart.combine(line_chart) 

# Insert the chart into the worksheet 
worksheet.insert_chart('E2', column_chart) 

workbook.close() 

輸出:

enter image description here

注意,這增加了第一個系列中的每個數據點的平均點。如果你願意,可以用兩點來做到這一點。

此外,相當於自己計算平均值,您可以讓Excel使用公式進行計算。例如用這種變化到上述程序:

# Add the worksheet data that the charts will refer to. 
headings = ['ID', ' Reading 1', ' Avg Reading 1'] 
data = [ 
    [0, 1, 2, 3, 4], 
    [4.2, 4.4, 4.5, 5.6, 1.2], 
    ['=AVERAGE($B$2:$B$6)'] * 5, 
] 

又見文檔的上combined charts在XlsxWriter部分。