问题的原因在于axlsx默认在绘制堆叠条形图时没有使用正确的颜色映射,因此需要手动指定颜色映射。以下是一个示例代码:
require 'axlsx'
ax = Axlsx::Package.new
wb = ax.workbook
wb.styles do |s|
red = s.add_style :bg_color => "FF0000"
blue = s.add_style :bg_color => "0000FF"
green = s.add_style :bg_color => "00FF00"
colors = [red, blue, green]
wb.add_worksheet(:name => "Stacked Bar Chart") do |sheet|
sheet.add_row ["", "Apples", "Oranges", "Bananas"]
sheet.add_row ["John", 8, 2, 5]
sheet.add_row ["Jane", 3, 1, 3]
sheet.add_row ["Mike", 2, 4, 4]
sheet.add_row ["Mark", 5, 3, 2]
sheet.add_chart(Axlsx::Bar3DChart, :start_at => 'A6', :end_at => 'H20') do |chart|
chart.add_series :data => sheet["B2:D2"], :colors => colors, :title => sheet["B1"]
chart.add_series :data => sheet["B3:D3"], :colors => colors, :title => sheet["B2"]
chart.add_series :data => sheet["B4:D4"], :colors => colors, :title => sheet["B3"]
chart.valAxis.label_rotation = -45
chart.catAxis.label_rotation = -45
end
end
end
ax.serialize('stacked_bar_chart_with_colors.xlsx')
在此示例中,我们使用了三个不同颜色的样式(red、blue和green),然后将它们作为colors参数传递给add_series方法。在这里,colors数组中的颜色将分别应用于每个系列的数据点。
下一篇:axlsx中的动态列数