使用openpyxl在KNIME中生成的图表Y轴数字不显示求助
openpyxl生成图表:Y轴不显示、格式异常问题解决
问题现象
- Y轴数字完全不显示,尝试设置标题、数字格式、缩放范围均无效
- 图表出现意外的圆角效果
- 图例与图表区域重叠,而非此前默认的侧边位置
- 此前正常状态:坐标轴自动适配,图例位于侧边
原生成代码
chart = LineChart() data = Reference(ws, min_col=start_column, max_col=end_column, min_row=start_row+8, max_row=end_row+6) categories = Reference(ws, min_col=start_column+1, max_col=end_column, min_row=start_row, max_row = start_row) chart.add_data(data, titles_from_data=True, from_rows=True) chart.set_categories(categories) # chart.switch_row_col = False out_cell_coord = "A" + str(cell.row + 2) chart.width = 13 chart.height =6.1 ws.add_chart(chart, out_cell_coord)
已尝试的无效操作
- 设置Y轴标题和数字格式:标题显示,但Y轴数字仍不显示
chart.y_axis.title = "Quantity" # Set the y-axis title chart.y_axis.numFmt = "0" # Display numbers without decimal places
- 重新实例化NumericAxis:无任何变化
chart.y_axis = NumericAxis()
- 设置Y轴缩放范围:图表尺寸适配,但Y轴数字依旧不显示
chart.y_axis.scaling.min = 0 chart.y_axis.scaling.max = 100
解决方案
1. 修复Y轴不显示问题
问题根源大概率是from_rows=True参数导致openpyxl错误隐藏了Y轴,或数据维度识别异常。可以从两方面调整:
- 显式强制Y轴可见:直接添加
chart.y_axis.visible = True,覆盖默认的隐藏设置 - 调整数据读取方式:如果你的数据结构是按列组织,去掉
from_rows=True,改用默认的按列读取数据,同时确认Reference的范围是否匹配数据布局 - 额外检查:确认
data引用的单元格范围是否包含有效数值,空值或非数值数据会导致Y轴无刻度生成
2. 移除圆角效果
openpyxl新版本可能默认启用了图表圆角,显式关闭即可:
from openpyxl.drawing.graphic import GraphicalProperties chart.graphicalProperties = GraphicalProperties(roundedCorners=False)
3. 修复图例重叠问题
强制设置图例到侧边,并调整图表内边距避免拥挤:
# 设置图例到右侧(可选l=左、t=上、b=下) chart.legend.position = "r" # 调整图表区域的尺寸和内边距,适配内容 chart.plot_area.width = 10 chart.plot_area.height = 5 chart.plot_area.left = 1 # 左内边距 chart.plot_area.top = 0.5 # 上内边距
完整调整后代码
from openpyxl.chart import LineChart, Reference from openpyxl.drawing.graphic import GraphicalProperties chart = LineChart() data = Reference(ws, min_col=start_column, max_col=end_column, min_row=start_row+8, max_row=end_row+6) categories = Reference(ws, min_col=start_column+1, max_col=end_column, min_row=start_row, max_row = start_row) # 调整数据添加方式,根据实际数据结构决定是否保留from_rows=True chart.add_data(data, titles_from_data=True) chart.set_categories(categories) # 强制显示Y轴并设置格式 chart.y_axis.visible = True chart.y_axis.title = "Quantity" chart.y_axis.numFmt = "0" chart.y_axis.scaling.min = 0 chart.y_axis.scaling.max = 100 # 关闭圆角效果 chart.graphicalProperties = GraphicalProperties(roundedCorners=False) # 设置图例位置并调整图表布局 chart.legend.position = "r" chart.width = 13 chart.height = 6.1 chart.plot_area.width = 10 chart.plot_area.height = 5 chart.plot_area.left = 1 chart.plot_area.top = 0.5 out_cell_coord = "A" + str(cell.row + 2) ws.add_chart(chart, out_cell_coord)
内容的提问来源于stack exchange,提问作者espinosaa11
相关产品推荐
相关产品推荐

