如何旋转和移动轴标题

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

我正在使用 openpyxl 库做一些图形。 我需要水平旋转它并移动到轴的顶部 这是我为轴制作标题的方法

chart.y_axis.title = "g²/Гц" if sheet.cell(row=2, column=columnOffset + col_index).value == "Sxx" else "g"
python openpyxl
1个回答
0
投票

您可以使用手动布局命令操纵图例位置 可能需要调整 x、y 和 h 设置,这些值可以是 0 到 1 之间的值。

示例代码使用条形图

import openpyxl
from openpyxl.chart.layout import Layout, ManualLayout
from openpyxl.chart import BarChart, Reference

# to create a new blank Workbook object
wb = openpyxl.Workbook()

# Get workbook active sheet from the active attribute.
sheet = wb.active

# write 2 to 12 in 1st column of the active sheet
for i in range(2, 13):
    sheet.append([i])

# Change the Y axis name
sheet['C2'].value = 'Sxx'
# Set the co-ords for the postion
columnOffset = 2
col_index = 1

# create data for plotting
values = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10)

# Create object of BarChart class
chart = BarChart()

# adding data to the Bar chart object
chart.add_data(values)

# set the title of the chart
chart.title = " BAR-CHART "

# set the title of the x-axis
chart.x_axis.title = " X_AXIS "

# set the title of the y-axis
chart.y_axis.title = "g²/Гц" if sheet.cell(row=2, column=columnOffset + col_index).value == "Sxx" else "g"

# Set chart Y axis text to horizontal orientation
chart.y_axis.txPr = chart.y_axis.title.text.rich
chart.y_axis.txPr.properties.vert = "horz"

# Move height of Y axis legend
chart.y_axis.title.layout = Layout(
    manualLayout=ManualLayout(
        h=0.85,  # value between 0 and 1
        x=0,
        y=0.9
    )
)

# Add Sheet chart
sheet.add_chart(chart, "E2")

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

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