Openpyxl,如何对x轴标签进行两项操作,旋转和更改字体,而不需要一个覆盖另一个

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

我的目标是旋转 x 轴上的标签并更改字体。但是,在下面的代码中,这两个操作单独工作,但是当我同时执行这两个操作时,旋转会因字体更改而撤消。

如何在我的图表上执行这两项操作?

import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, Font as Font2

# 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 "

 # Rotate X-axis labels, operation 1
chart.x_axis.txPr = chart.x_axis.title.text.rich
chart.x_axis.txPr.properties.rot = "-2700000"
chart.x_axis.title = None

# Adjust font, operation 2, 
font_ = Font2(typeface='Avenir Next LT Pro')
cp = CharacterProperties(latin=font_, sz=900)
chart.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])

sheet.add_chart(chart, "E2")
 
# save the file
wb.save("barChart.xlsx")
python excel openpyxl
1个回答
0
投票

像这样重新排列代码的最后几行;

# Adjust font, operation 2,
font_ = Font2(typeface='Avenir Next LT Pro')
cp = CharacterProperties(latin=font_, sz=900)

# Rotate X-axis labels, operation 1
chart.x_axis.txPr = chart.x_axis.title.text.rich

chart.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])
chart.x_axis.txPr.properties.rot = "-2700000"

chart.x_axis.title = None

sheet.add_chart(chart, "E2")

# save the file
wb.save("barChart2.xlsx")

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