c# Chart(System.Web.UI.DataVisualization//System.windows.Forms)

2 篇文章 0 订阅

在C#中,chart算是较为老一点的东西,但是确实是很好用的一个组件,它有两种方式去调用,但是原理是相同的,这两种不同的方式便是System.Web.UI.DataVisualization 和 System.windows.Forms.

创建成功一个chart其实不难。以下是主要的组成部分。

1. new 一个chart.---这就相当于是一个画布给到你。

2.new 一个 chartArea. 添加到1中的chart上。-----设置你画图的区域。

3. new 一个series. 添加到1中的chart上。-------series放置的是你需要显示的数据。

4. new 一个 legend, 添加到1中的chart上-------用于显示对应数据的一个descript。

通过这四者或者前三者就可以创建出一个简单的chart.

以下就是我创建的一个chart.

 public static void DrawCharts(Dictionary<string, List<PerfPepilineResult>> result, string path, string title, bool daily)
        {
            Chart chart = new Chart();
            //default
            chart.Width = 1000;
            chart.Height = 500;
            chart.RenderType = RenderType.ImageTag;
            chart.Palette = ChartColorPalette.BrightPastel;
            chart.Font.Bold = true;
            Title t = new Title();
            t.Text = title;
            t.Docking = Docking.Top;
            t.Font = new Font("Trebuchet MS", 14, FontStyle.Bold);
            t.ForeColor = Color.Black;
            chart.Titles.Add(t);

            //chartArea
            ChartArea chartArea = new ChartArea("test for PerfPepiline");
            chartArea.BorderColor = Color.Black;
            chartArea.BorderWidth = 2;
            //X
            chartArea.AxisX.Title = "Date";
            chartArea.AxisX.TitleFont = new Font("Times New Roman", 14f, FontStyle.Regular);
            chartArea.AxisX.TitleForeColor = Color.Black;
            chartArea.AxisX.LineColor = Color.Black;
            chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
            //Y
            chartArea.AxisY.Title = "Value";
            chartArea.AxisX.LineColor = Color.Black;
            chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisY.TitleFont = new Font("Times New Roman", 14f, FontStyle.Regular);
            chartArea.AxisY.TitleForeColor = Color.Black;

            //data  series
            chart.Series.Clear();
           //数据处理

            CreateSeriesAndLegend(chart, color, item.logDate, item.Percentile95, item.Name);
            }
            //save
            chart.ChartAreas.Add(chartArea);
            chart.SaveImage(path, ChartImageFormat.Png);
        }

        public static List<ChartModel> GetpointList(out List<DateTime> MaxAndMinX, out List<int> MaxAndMinY, Dictionary<string, List<PerfPepilineResult>> result)
        {
            var pointList = new List<ChartModel>();
            //数据处理
            #endregion
            return pointList;
        }

        public static void CreateSeriesAndLegend(Chart chart, Color color, List<DateTime> txData, List<int?> tyData, string legendName)
        {
            Series series = new Series();
            series.Name = legendName;
            series.XValueType = ChartValueType.DateTime;
            series.YValueType = ChartValueType.Int32;
            series.ChartType = SeriesChartType.Spline;
            series.Points.DataBindXY(txData, tyData);

            series.Color = color;
            series.BorderWidth = 2;
            series.MarkerBorderColor = color;
            series.MarkerBorderWidth = 2;
            series.MarkerColor = color;
            series.MarkerSize = 4;
            series.MarkerStyle = MarkerStyle.Circle;
            chart.Series.Add(series);

            Legend legend = new Legend();
            legend.Name = legendName;
            legend.ForeColor = Color.Black;
            legend.Docking = Docking.Top;
            legend.Alignment = StringAlignment.Far;
            chart.Legends.Add(legend);

        }     


    }

 

另外补充一个读取配置文件获取数据绘制chart的代码。

1.tools 

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApp4
{
    public class WebSnapshotsHelper
    {
        Bitmap m_Bitmap;
        string m_Url;
        int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;
        public WebSnapshotsHelper(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
        {
            m_Url = Url;
            m_BrowserHeight = BrowserHeight;
            m_BrowserWidth = BrowserWidth;
            m_ThumbnailWidth = ThumbnailWidth;
            m_ThumbnailHeight = ThumbnailHeight;
        }
        public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
        {
            WebSnapshotsHelper thumbnailGenerator = new WebSnapshotsHelper(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
            return thumbnailGenerator.GenerateWebSiteThumbnailImage();
        }
        public Bitmap GenerateWebSiteThumbnailImage()
        {
            Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();
            m_thread.Join(60000);
            return m_Bitmap;
        }
        private void _GenerateWebSiteThumbnailImage()
        {
            WebBrowser m_WebBrowser = new WebBrowser();
            m_WebBrowser.ScrollBarsEnabled = false;
            m_WebBrowser.Navigate(m_Url);
            m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            m_WebBrowser.Dispose();
        }
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            WebBrowser m_WebBrowser = (WebBrowser)sender;
            m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);

        }
    }
}

2. 主方法

using ConsoleApp4.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string alljson = File.ReadAllText("./Resources/SnR_InternalLatency.json");
                string coreuxprodbn2bJson = File.ReadAllText("./Resources/coreux-prod-bn2b.json");
                string coreuxprodch1bJson = File.ReadAllText("./Resources/coreux-prod-ch1b.json");
                string coreuxprodco4Json = File.ReadAllText("./Resources/coreux-prod-co4.json");
                Dictionary<string,string> dataCollect = new Dictionary<string, string>();
                dataCollect.Add("SnR_InternalLatency, Percentile95", alljson);
                dataCollect.Add("SnR_InternalLatency, coreux-prod-bn2b, Percentile95", coreuxprodbn2bJson);
                dataCollect.Add("SnR_InternalLatency, coreux-prod-ch1b, Percentile95", coreuxprodch1bJson);
                dataCollect.Add("SnR_InternalLatency, coreux-prod-co4, Percentile95", coreuxprodco4Json);
                List<SeriesInfo> pointsSet = new List<SeriesInfo>();
                foreach (KeyValuePair<string, string> data in dataCollect)
                {
                    var payload = JObject.Parse(data.Value)["QueryResults"];
                    // set up some data
                    List<DateTime> xvalsList = new List<DateTime>();
                    foreach (var item in payload)
                    {
                        xvalsList.Add(DateTime.Parse(item["LogDate"].ToString()));

                    }
                    var xvals = xvalsList.ToArray();
                    List<int> yvalsList = new List<int>();
                    foreach (var item in payload)
                    {
                        yvalsList.Add(Convert.ToInt32(item["Percentile95"].ToString()));

                    }
                    var yvals = yvalsList.ToArray();
                    pointsSet.Add(new SeriesInfo() { yAxis=yvals,xAxis=xvals, Name= data.Key });

                }
                // create the chart
                var chart = new Chart();
                chart.Size = new Size(1800, 800);
                var chartArea = new ChartArea();
                chartArea.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
                chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
                chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
                chartArea.AxisX.LabelStyle.Font = new Font("Consolas", 8);
                chartArea.AxisY.LabelStyle.Font = new Font("Consolas", 8);
                chartArea.AxisY.Minimum = 67;
                chartArea.AxisY.Interval = 1;
                chartArea.AxisY.Title = "Value";
                chartArea.AxisX.Title = "Date";
                chartArea.AxisX.TitleFont= new Font("Consolas", 14);
                chartArea.AxisY.TitleFont = new Font("Consolas", 14);
                chart.ChartAreas.Add(chartArea);
                foreach (SeriesInfo seriesInfo in pointsSet)
                { 
                    Series series = new Series();
                    series.Name = seriesInfo.Name;
                    series.LegendText = seriesInfo.Name;
                    series.ChartType = SeriesChartType.Spline;
                    series.MarkerStyle = MarkerStyle.Circle;
                    series.XValueType = ChartValueType.DateTime;
                    if (series.Name.Equals("SnR_InternalLatency, Percentile95")) { series.Color = Color.LightSteelBlue; }
                    if (series.Name.Equals("SnR_InternalLatency, coreux-prod-bn2b, Percentile95")) { series.Color = Color.DarkOrange; }
                    if (series.Name.Equals("SnR_InternalLatency, coreux-prod-ch1b, Percentile95")) { series.Color = Color.SteelBlue; }
                    if (series.Name.Equals("SnR_InternalLatency, coreux-prod-co4, Percentile95")) { series.Color = Color.SandyBrown; }
                    chart.Series.Add(series);
                    // bind the datapoints
                    chart.Series[seriesInfo.Name].Points.DataBindXY(seriesInfo.xAxis, seriesInfo.yAxis);
                    Legend legend = new Legend();
                    legend.Name = series.Name;
                    legend.ForeColor = Color.Black;
                    legend.Docking = Docking.Top;
                    legend.Alignment = StringAlignment.Far;
                    chart.Legends.Add(legend);
                }
                
                // draw!
                chart.Invalidate();
                // write out a file
                chart.SaveImage("chart.png", ChartImageFormat.Png);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

希望能够帮助到看到的人。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值