LoginSignup
1
0

More than 1 year has passed since last update.

openpyxlでグラフの凡例を一部項目だけ消したい

Last updated at Posted at 2022-10-15

Excelのグラフ(散布図)を作るとき、指定した横軸座標を示す縦棒(カーソル)を入れたくなることがあります。
散布図の系列として縦線を追加すればいいのですが、そのままでは凡例に余計な項目が表示されてしまうのが気に入りません。

そこで、openpyxlでグラフを生成し、カーソルとなる線を追加した後にその凡例の項目を消すように試みました。

import math
import openpyxl

xax = list(range(360))
values = [
    ['', *xax]
    ,['sin', *[math.sin(x*math.pi/180) for x in xax]]
    ,['cos', *[math.cos(x*math.pi/180) for x in xax]]
]

wb = openpyxl.Workbook()
ws = wb.active
for l in values:
    ws.append(l)

chart = openpyxl.chart.ScatterChart()   #散布図
chart.anchor = 'A7' #chart挿入先セル
chart.y_axis.scaling.min = -1.5 #y軸最小値
chart.y_axis.scaling.max = 1.5  #y軸最大値

#データ系列追加
xvalues = openpyxl.chart.Reference(ws, min_col=2, max_col=361, min_row=1)
for id in range(len(values)-1):
    values = openpyxl.chart.Reference(ws, min_col=1, max_col=361, min_row=id+2)
    series = openpyxl.chart.Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

#カーソル追加
for ic, v in enumerate([135, 180]):
    id+=1
    eq = '=B' + str(ws.max_row + 1)
    l = ['cursor' + str(ic+1), v, eq, eq, -1.5, 1.5]
    ws.append(l) 
    xvalues = openpyxl.chart.Reference(ws, min_col=3, max_col=4, min_row=id+2)
    values = openpyxl.chart.Reference(ws, min_col=5, max_col=6, min_row=id+2)
    series = openpyxl.chart.Series(values, xvalues, title_from_data=False)
    chart.series.append(series)
    chart.legend.legendEntry.append(openpyxl.chart.legend.LegendEntry(idx=id, delete=True)) #legend項目消去

ws.add_chart(chart)
wb.save('chartCursors.xlsx')

LibreOffice Calc で開くと期待通りの結果になったのですが、
image.png

Excelでは凡例の項目が消えてくれませんでした。
image.png

どうやら、同じ現象に悩んでいる人もいるようで、xlsxファイルの中身(XML)は正しく生成されていても、Excelが正しく表示してくれない(?)ようです。
https://foss.heptapod.net/openpyxl/openpyxl/-/issues/1604

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0