使用 Openpyxl 在 Excel 中更改折线图的图表样式

问题描述 投票:0回答:1

我有以下代码来导出一组数据帧,然后将它们转换为 Excel 中的表格并应用颜色格式,然后它为每个表格创建线图,一切正常,但我遇到了以下问题:

  • 应用样式 12
  • 将数据标签放置到“上方”
  • 删除主要网格线

这就是我得到的

这就是我需要的!没有主要网格线和数据标签的样式 12 Avobe

        # Load the existing workbook
        workbook = openpyxl.load_workbook(output_path + '\\' + output_file)

        # Get the 'USA (TM)' sheet or create it if it doesn't exist
        sheet_name = s
        if sheet_name not in workbook.sheetnames:
            workbook.create_sheet(sheet_name)
        sheet = workbook[sheet_name]

        # Assuming 'df' is your DataFrame

        # Write headers to the specified sheet starting from column F, row 1
        headers = merged_cc.columns.tolist()
        for idx, header in enumerate(headers, start=1):
            sheet.cell(row=1, column=idx + columns_position[e] - 1, value=header)

        # Write the DataFrame values to the specified sheet starting from column F, row 2
        for r_idx, row in enumerate(merged_cc.iterrows(), start=2):
            for c_idx, value in enumerate(row[1], start=1):
                sheet.cell(row=r_idx, column=c_idx + columns_position[e] -1 , value=value)
                if isinstance(value, (int, float)):
                    sheet.cell(row=r_idx, column=c_idx + columns_position[e] -1).number_format = '0%'

        # Adjust cell width of the table to specific width
        for idx, column_width in enumerate([10.71, 10.71,10.71, 10.71, 10.71], start=columns_position[e]):  # Example widths
            column_letter = openpyxl.utils.get_column_letter(idx)
            sheet.column_dimensions[column_letter].width = column_width


        # Replace 'A1:B10' with the range you want to convert
        table_range = w

        # Check if the table name already exists
        existing_tables = sheet.tables
        if table_name in existing_tables:
            del sheet._tables[table_name]
        
        # Format the range as a table
        table = openpyxl.worksheet.table.Table(displayName=table_name, ref=table_range)
        table.tableStyleInfo = TableStyleInfo(name="TableStyleMedium13", showFirstColumn=False,
               showLastColumn=False, showRowStripes=True, showColumnStripes=False)
        # Add the table to the worksheet
        sheet.add_table(table)

        # Create Graph *

        # Create a new LineChart object
        chart = LineChart()

        # Add data to the chart
        data = Reference(sheet, min_col=columns_position[e]+2, min_row=1, max_col=columns_position[e] + 4, max_row=sheet.max_row)
        chart.add_data(data, titles_from_data=True)

        # Set the categories (X-axis labels)
        categories = Reference(sheet, min_col=columns_position[e] + 1, min_row=2, max_row=len(merged_cc)+1)
        chart.set_categories(categories)

        # Set the title of the chart
        chart.title = companies[e]
        chart.style = 12
        '''
        # Create a DataLabelList object
        data_labels = DataLabelList()
        data_labels.showVal = True  # Show the values of the data points

        # Set the data labels for the chart
        chart.dLbls = data_labels

        # Iterate through each series in the chart
        for series in chart.series:
            # Set data labels for each data point in the series
            for point in series:
                data_label = DataLabel(idx=point.index, showVal=True, position='above')  # Position data label above the data point
                point.dataLabel = data_label

        # Add the chart to the worksheet
        '''
        sheet.add_chart(chart, graph_coordenades[e])  # Adjust the cell reference as needed
        # Save the workbook
        workbook.save(output_path + '\\' + output_file)
python excel charts openpyxl linegraph
1个回答
0
投票

当您声明样式 12 时,不确定您在寻找什么,但为了在第二个屏幕截图中复制我认为您所需的视图,您可以指定大部分要求。

鉴于您的代码无法运行,我提供了一个独立示例,用于设置所需的图表属性,以便您可以根据需要添加到代码中。

from openpyxl import Workbook
from openpyxl.chart.label import DataLabelList
from openpyxl.chart import (
    LineChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

min_col = 2
max_col = 5
marker_size = 8

"""
This section just adds some data to the Sheet in the format of that used from the screen shot
"""
rows = [
    ('Quarter', 'FQ2 2022', 'FQ4 2022', 'FQ2 2023', 'FQ4 2023'),
    ('R1', 0.51, 0.53, 0.56, 0.58),
    ('R2', 0.26, 0.27, 0.28, 0.31),
    ('R3', 0.07, 0.08, 0.08, 0.1),
]
for r in rows:
    ws.append(r)

for row in ws.iter_rows(min_row=2, min_col=min_col, max_row=4, max_col=max_col):
    for cell in row:
        cell.number_format = '0%'
# ----------------------------------------------------------------- #

### Create Line chart
l_chart1 = LineChart()

### Set data and line colour and markers for first row data
s1_line_colour = "0000FF"
data1 = Reference(ws, min_col=min_col, min_row=2, max_col=max_col, max_row=2)
series1 = Series(data1, title='Unaided Awareness')  # or reference a cell
series1.graphicalProperties.line.solidFill = s1_line_colour
series1.marker.symbol = "circle"
series1.marker.size = marker_size
series1.marker.graphicalProperties.solidFill = s1_line_colour # Marker filling
series1.marker.graphicalProperties.line.solidFill = s1_line_colour # Marker outline
### Add Series1 to the chart
l_chart1.append(series1)

### Set data and line colour and markers for second row data
s2_line_colour = "FF0000"
data2 = Reference(ws, min_col=min_col, min_row=3, max_col=max_col, max_row=3)
series2 = Series(data2, title='Unaided Consideration')
series2.graphicalProperties.line.solidFill = s2_line_colour
series2.marker.symbol = "circle"
series2.marker.size = marker_size
series2.marker.graphicalProperties.solidFill = s2_line_colour
series2.marker.graphicalProperties.line.solidFill = s2_line_colour
### Add Series2 to the chart
l_chart1.append(series2)

### Set data and line colour and markers for third row data
s3_line_colour = "00FF00"
data3 = Reference(ws, min_col=min_col, min_row=4, max_col=max_col, max_row=4)
series3 = Series(data3, title='Unaided Preference')
series3.graphicalProperties.line.solidFill = s3_line_colour
series3.marker.symbol = "circle"
series3.marker.size = marker_size
series3.marker.graphicalProperties.solidFill = s3_line_colour
series3.marker.graphicalProperties.line.solidFill = s3_line_colour
### Add Series3 to the chart
l_chart1.append(series3)

### Set Chart Style
# l_chart1.style = 12  # Can be set but will not affect chart 

### Set x-axis names
x_values = Reference(ws, min_col=2, min_row=1, max_col=max_col, max_row=1)
l_chart1.set_categories(x_values)

### Set y-axis Gridlines and number format
l_chart1.y_axis.minorGridlines = None
l_chart1.y_axis.majorGridlines = None
l_chart1.y_axis.number_format = '0%'

### Set Chart title 
l_chart1.title = 'Store 1'

### Set position for the Legend
l_chart1.legend.position = 'b'

### Set Datalables above the markers
l_chart1.dataLabels = DataLabelList()
l_chart1.dataLabels.showVal = True
l_chart1.dataLabels.position = 't'

### Add Chart to Excel Sheet
ws.add_chart(l_chart1, "F1")

### Save Sheet
wb.save("LineChart.xlsx")

这将导致图表如下

您还提到您希望“没有主要网格线”,但是您帖子中的屏幕截图中的图表有主要网格线,但没有 X 或 Y 轴线。
上面的示例删除了主要和次要网格线(如果您需要的话)。删除 X 和 Y 轴线可能是可能的,需要进一步检查。

© www.soinside.com 2019 - 2024. All rights reserved.