我有一個Windows窗體應用程序,用於顯示存儲在數據庫中的數據的圖形。我能夠將數據顯示在條形圖或餅圖中。但是條形圖中的圖例只顯示系列的名稱「Series1」。餅圖的圖例顯示了系列數據的正確圖例。我搜索了MSDN,發現了幾篇關於添加圖例的文章,但它們都有相同的結果。如何獲取系列數據以條形圖圖例顯示
這裏是我的條形圖代碼:
string[] xvals = new string[dt.Rows.Count];
int[] yvals = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
xvals[i] = dt.Rows[i]["XValues"].ToString();
yvals[i] = Convert.ToInt32(dt.Rows[i]["YValues"].ToString());
}
Chart barChart = new Chart();
ChartArea chartArea = new ChartArea();
barChart.ChartAreas.Add(chartArea);
barChart.Dock = DockStyle.Fill;
barChart.BackColor = Color.Transparent;
barChart.Palette = ChartColorPalette.Fire;
barChart.ChartAreas[0].BackColor = Color.Transparent;
barChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
barChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
Series series1 = new Series
{ Name = "Series1", IsVisibleInLegend = true, ChartType = SeriesChartType.Bar };
series1.ChartType = SeriesChartType.Column;
barChart.Series.Add(series1);
for (int i = 0; i < dt.Rows.Count; i++)
{
series1.Points.AddXY(dt.Rows[i]["XValues"].ToString(),
Convert.ToInt32(dt.Rows[i]["YValues"].ToString()));
var p1 = series1.Points[i];
p1.Color = Color.FromArgb((byte)r.Next(90, 255), (byte)r.Next(90, 255), 160);
}
barChart.Legends.Add(new Legend("Legend1"));
barChart.Legends["Legend1"].BackColor = Color.Transparent;
barChart.Series["Series1"].Legend = "Legend1";
series1.IsVisibleInLegend = true;
gbo1.Controls.Add(barChart);
這裏是我的餅圖代碼:
string[] xvals = new string[dt.Rows.Count];
int[] yvals = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
xvals[i] = dt.Rows[i]["XValues"].ToString();
yvals[i] = Convert.ToInt32(dt.Rows[i]["YValues"].ToString());
}
Chart pieChart = new Chart();
ChartArea chartArea = new ChartArea();
chartArea.Name = "PieChartArea";
pieChart.ChartAreas.Add(chartArea);
pieChart.Dock = DockStyle.Fill;
pieChart.Location = new Point(0, 50);
pieChart.Palette = ChartColorPalette.Fire;
pieChart.BackColor = Color.Transparent;
pieChart.ChartAreas[0].BackColor = Color.Transparent;
Series series2 = new Series
{ Name = "Series2", IsVisibleInLegend = true, ChartType = SeriesChartType.Pie };
pieChart.Series.Add(series2);
for (int i = 0; i < dt.Rows.Count; i++)
{
series2.Points.Add((int)dt.Rows[i]["YValues"]);
var p2 = series2.Points[i];
p2.Color = Color.FromArgb((byte)r.Next(90, 255), (byte)r.Next(90, 255), 160);
p2.LegendText = dt.Rows[i]["XValues"].ToString();
}
pieChart.Legends.Add(new Legend("Legend2"));
pieChart.Legends["Legend2"].BackColor = Color.Transparent;
pieChart.Series["Series2"].Legend = "Legend2";
series2.IsVisibleInLegend = true;
gboReport1.Controls.Add(pieChart);
我缺少什麼?請幫忙。
這裏是條形圖的輸出: Bar Chart with bad Legend
下面是餅圖的輸出: Pie Chart with good Legend
您使用哪種圖表API? –
這是你的意思:使用System.Windows.Forms.DataVisualization.Charting; –