excel Openpyxl中的图表设计,颜色轴标题

y1aodyip  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(109)

下面的代码使用openpyxl生成了一个简单的条形图。

我希望能够在Y轴上着色标题。但我找不到一个有效的解决方案。有人知道怎么做吗?
我的目标很简单:

import openpyxl
from openpyxl.chart import BarChart, Reference

# Create a workbook and activate a sheet
wb = openpyxl.Workbook()
sheet = wb.active

# insert some categories
cell = sheet.cell(row=1, column=1)
cell.value = 'Category 1.1' 
cell = sheet.cell(row=2, column=1)
cell.value = 'Category 1.2 - limit'
cell = sheet.cell(row=3, column=1)
cell.value = 'Category 2'
cell = sheet.cell(row=4, column=1)
cell.value = 'Category 2.1 - extra'
cell = sheet.cell(row=5, column=1)
cell.value = 'Category 2.2 - extra2'

# insert some values
for i in range(5):
    cell = sheet.cell(row=i+1, column=2)
    cell.value = i+2

# create chart
chart = BarChart()

values = Reference(sheet, min_col = 2, min_row = 1,
                         max_col = 2, max_row = 5)

bar_categories = Reference(sheet, min_col=1, min_row=1, max_row=5)
chart.add_data(values)
chart.set_categories(bar_categories)

chart.title = " BAR-CHART "
chart.legend = None
chart.x_axis.title = " X_AXIS "
chart.y_axis.title = " Y_AXIS "
sheet.add_chart(chart, "E2")
 
# save the file
wb.save("barChart.xlsx")
nkkqxpd9

nkkqxpd91#

一个可能的选择是通过 *Advanded Chart * 重用xml:

from openpyxl.chart.text import RichText
from openpyxl.xml.functions import fromstring

# y-title text properties
yt_name, yt_color = "Y_AXIS", "ff0000"

xml = f"""
<txPr>
  <a:p xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
    <a:r>
       <a:rPr b="1" i="0" sz="1000" spc="-1" strike="noStrike">
          <a:solidFill>
             <a:srgbClr val="{yt_color}" />
          </a:solidFill>
          <a:latin typeface="Calibri" />
       </a:rPr>
       <a:t>{yt_name}</a:t>
    </a:r>
  </a:p>
</txPr>
"""

chart.y_axis.title.tx.rich = RichText.from_tree(fromstring(xml))

输出量:

相关问题