如何在 SpreadsheetGear 中使用 Y 轴标签的名称创建水平条形图?

How do I Create a Horizontal Bar Chart in SpreadsheetGear with Names for the Y-Axis Labels?

假设我的电子表格中有一个行星名称列表和行星与太阳的距离(第 2 列以百万英里为单位 - 最近距离 UniverseToday.com):

如何在 SpreadsheetGear 中创建一个水平条形图,其中行星名称位于 y 轴上,水平条显示与太阳的距离。

您需要创建类型为 ChartType.BarClustered 的图表才能执行此操作。如果您尝试从头开始创建这样的图表,将涉及各种 API 来完成此操作。如果您正在寻找一个完整的示例作为演示,我在本文底部提供了一个 post。

要查看的相关 API 和文档可能包括以下内容(一定要查看其中一些界面,因为您会发现更多选项可以通过此处未展示的各种其他方式自定义您的图表):

更新:添加了一些代码来反转系列的情节顺序,这将匹配源数据的行顺序。

示例:

using SpreadsheetGear;
using SpreadsheetGear.Charts;
...

// Setup a workbook with desired data.
IWorkbook workbook = Factory.GetWorkbook();
IWorksheet worksheet = workbook.ActiveWorksheet;
IRange cells = worksheet.Cells;
cells["A1:B6"].Value = new object[,] {
    { "Planet", "Distance from Sun\n(millions of miles)" },
    { "Mercury", 10 },
    { "Venus", 66 },
    { "Earth", 91 },
    { "Mars", 127 },
    { "Jupiter", 460 }};

// Create a chart object.
IChart chart = worksheet.Shapes.AddChart(125, 5, 400, 200).Chart;

// Set the source data to the above range.
chart.SetSourceData(cells["A1:B6"], RowCol.Columns);

// Specify chart type.
chart.ChartType = ChartType.BarClustered;

// Add a chart title.
chart.HasTitle = true;
chart.ChartTitle.Text = "Planet Distances from Sun";

// Remove legend.
chart.HasLegend = false;

// Set some options on the series, such as adding data labels and
// specifying the position of the data labels.
ISeries series = chart.SeriesCollection[0];
series.HasDataLabels = true;
series.DataLabels.Position = DataLabelPosition.OutsideEnd;

// Access the "value" axis (the X-Axis in this case) to set the
// title to indicate values are in millions.
IAxis valueAxis = chart.Axes[AxisType.Value];
valueAxis.HasTitle = true;
valueAxis.AxisTitle.Text = "(Millions of miles)";

// Access the "category" axis (the Y-Axis in this case).
IAxis catAxis = chart.Axes[AxisType.Category];
// Reverse the plot order (top-top-bottom instead of bottom-to-top).
catAxis.ReversePlotOrder = true;
// Note that enabling ReversePlotOrder on its own will also move your
// "value" axis labels to the top of the chart since this axis will by
// default cross at the first-plotted category item.  To fix this you 
// need to tell it to cross at the maximum category item, which would
// correspond to the bottom of the chart.
catAxis.Crosses = AxisCrosses.Maximum;

// Save workbook to file.
workbook.SaveAs(@"C:\temp\BarChart.xlsx", FileFormat.OpenXMLWorkbook);