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

时间:2016-06-22 19:58:36

标签: charts spreadsheetgear

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

  • 火星10
  • Venus 66
  • 地球91
  • 火星127
  • Jupiter 460

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

1 个答案:

答案 0 :(得分:1)

您需要创建一个ChartType类型的图表.BarClustered执行此操作。如果您尝试从头开始创建此类图表,则需要使用各种AP​​I来实现此目的。如果您正在寻找一个完整的示例作为演示,我在本文的底部提供了一个。

要查看的相关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);