如何在openpyxl中删除图例名称

2024-05-23 22:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

--------------代码片段-----------------

代码是这样的。这里有一些创建条形图的代码

# create barChart

barChart= BarChart()
barChartData= Reference(worksheet, min_col=min_col, max_col=max_col, min_row=min_row, max_row=max_row)
barChart.add_data(bar_chart_data, from_rows=True, titles_from_data=True)

barChart.legend.position = 't'

。。。 然后有一些代码来创建折线图

# create lineChart
lineChart= LineChart()
lineChartData= Reference(worksheet, min_col=min_col + 1, max_col=max_col, min_row=max_row + 1,
                               max_row=max_row + 1)
lineChart.add_data(compare_chart_data, from_rows=True)

。。。 然后有一些代码将折线图添加到条形图的顶部

# combine both charts on top of each other
lineChart.y_axis.crosses = "min"
barChart+= lineChart

--------------代码段结束-------------------

所以发生的事情是,这张图表产生了一个图例,上面写着

  • 香蕉
  • 苹果
  • 橙子
  • 系列4

香蕉、苹果和橙子是条形图数据系列的名称。系列4,应该是折线图的图例。我想把它移除,我试着做了以下几项

我是python新手,不知道如何删除openpyxl创建的表中的图例“Series 4”

barChart += lineChart

我尝试过设置下面的代码(添加后),但它删除了所有内容

barChart.legend = None

我也尝试过设置下面的代码(在添加之前),但它什么也不做

lineChart.legend = None

不知怎的,我觉得它在添加过程中自动创建了传奇名称系列4

为了测试,我试着设置

titles_from_data = True

但这只是将图例名称更改为0%

我不想把它设为另一个值,我只想去掉它

----更新---

我在WBM推荐的评论部分找到了一个链接,用于尝试更新LegendEntry属性中的记录。看起来像这样

bar_chart.legend.LegendEntry = [(openpyxl.chart.legend.LegendEntry(3, delete=1))]

还是没有用

为了便于调查,我尝试在添加上述代码之前和之后打印LegendEntry属性的内容

在添加代码之前,令人惊讶的是,结果是空的

[]

在我添加代码之后,它看起来像这样

Parameters: [idx=3, delete=True, txPr=None]

尽管LegendEntry已更新,但输出仍保持不变:

  • 香蕉
  • 苹果
  • 橙子
  • 系列4

Tags: 代码fromtruedatachartcolminmax
2条回答

我正在使用OpenPYXL3.0.9

查看源代码以获得一个想法,并实现了这一点:

import openpyxl
chart.x_axis = openpyxl.chart.axis.TextAxis(delete=True)

下面是更多的代码:

CHART_ROW = 11
CHART_HEIGHT = 12
DATA_TABLE_START_ROW = 34
LENGTH_DIST_START_COL = 1
SPACER_DIST_START_COL = LENGTH_DIST_START_COL + 10
SPACER_RANGE_START_COL = SPACER_DIST_START_COL + 6

    chart = BarChart()
    chart.style = style  # 1 = black line, 13 = green bold line
    chart.title = "Spacer Distribution Summary"
    chart.height = CHART_HEIGHT  # default is 7.5
    chart.width = 7  # default is 15
    chart.y_axis.title = 'Target Spacer Frequency'
    chart.x_axis = openpyxl.chart.axis.TextAxis(delete=True)

    values = Reference(self.sheet,
                       min_col=SPACER_DIST_START_COL + 1,
                       max_col=SPACER_DIST_START_COL + 1,
                       min_row=self.spacer_distribution_first_row,
                       max_row=self.spacer_distribution_last_row)
    series = Series(values, title_from_data=False)
    chart.series.append(series)
    # chart.legend = None
    pos = f"{column_string(SPACER_DIST_START_COL)}{CHART_ROW}"
    self.sheet.add_chart(chart, pos)

根据openpyxl documentation的错误代码,我们找到了以下用法:

openpyxl.chart.legend.Legend(legendEntry=())

因此,在Legenentry中输入要更新地物的列表。我相信在你的情况下,这将是

chartABC.legend.Legend(legendEntry=(['test', 'test', 'test']))

相关问题 更多 >