python 如何在x轴标签上进行两个操作,旋转和更改字体,而不会一个覆盖另一个

4smxwvx5  于 2023-10-15  发布在  Python
关注(0)|答案(1)|浏览(68)

我的目标是在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")
ffscu2ro

ffscu2ro1#

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

### 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("barChart.xlsx")

相关问题