【问题标题】:Adding legend to winforms point chart将图例添加到 winforms 点图
【发布时间】:2018-08-22 03:56:14
【问题描述】:

我正在使用 C# 构建一个 winform 点图,其中数据来自数据表。我已经创建了这样的点:

chart1.Series.Add("series1");
chart1.Series["series1"].ChartType = SeriesChartType.Point;
chart1.Series["series1"].YValueMembers = "VALUE";
chart1.Series["series1"].XValueMember = "DATE";
chart1.DataSource = dt;

我希望能够根据数据表 dt 中名为 product.我已经尝试了很多方法来完成这项工作,但没有任何效果。我怎样才能做到这一点?

【问题讨论】:

  • 这是饼图吗?默认情况下,其他类型将每个系列显示一个 legendItem。如果您想要不同的东西,例如每个点的图例项,您将需要创建一个新图例以及代码中的所有项。 Here is an example 创建自定义图例。 - 顺便说一句,您将无法在图例上使用数据绑定。 - 请详细说明你想要什么..!
  • 今天早上我意识到我的问题 - 我将更新/回答我自己的问题以供将来参考。谢谢!

标签: c# winforms charts


【解决方案1】:

你可以使用我从msdn page得到的这段代码

// Create a new legend called "Legend2".
chart1.Legends.Add(new Legend("Legend2"));

// Set Docking of the Legend chart to the Default Chart Area.
chart1.Legends["Legend2"].DockToChartArea = "Default"; 

// Assign the legend to Series1.
chart1.Series["Series1"].Legend = "Legend2";
chart1.Series["Series1"].IsVisibleInLegend = true;

【讨论】:

    【解决方案2】:

    我的部分问题是首先要了解如何构建图表。我意识到我需要为我的数据表中的每个独特产品创建一个系列并将它们添加到图表中。我首先在数据表中列出了独特的产品:

            List<string> products = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                if (!products.Contains(row["product"].ToString()))
                {
                    products.Add(row["product"].ToString());
                }
            }
    

    然后

           foreach (string product in products)
            {
                string seriesName = product;
                chart1.Series.Add(seriesName);
                DataTable dtprod = new DataTable();
                dtprod = dt.Select("product= '" + product + "'").CopyToDataTable();
                chart1.Series[seriesName].ChartType = SeriesChartType.Point;
                chart1.Series[seriesName].YValueMembers = "VALUE";
                chart1.Series[seriesName].XValueMember = "DATE";
                chart1.Series[seriesName].Points.DataBindXY(dtprod.Rows,"DATE", dtprod.Rows, "VALUE");
                chart1.Series[seriesName].XValueType = ChartValueType.DateTime;
                chart1.Series[seriesName].MarkerSize = 10;
            }
    

    这为每个产品生成了一个带有唯一标记的点图。感谢您的回答!

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2019-05-08
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-05-11
      • 2021-09-23
      • 2021-02-22
      相关资源
      最近更新 更多