I want to make a survey with asp.net and c#.
It is clear that I can do it. But for the results I want to show them in a pie-chart and histogram.
The questions have only two answers "yes" and "no".
In pie-chart the whole percentage of "yes" and percentage of "no" like %55 "yes", %45 "no".
In histogram I want to show each question which is divided into 2 part ("yes" and "no").
In order to do these (pie-chart and the histogram), should I use component like Telerik?
Or can I do this with drawing library in .NET?
You can use Asp.net Chart controls for representing the data in pie charts......and it also depends on databinding.
if you are using datatable to get data from database then asp.net chart controls much better ...
would you pls take a look at this link for more information....
https://web.archive.org/web/20211020111731/https://www.4guysfromrolla.com/articles/120804-1.aspx
EDIT
This is function getting data from database..
public DataTable GetVisits(System.DateTime startdate , System.DateTime enddate)
{
const string sql = #"SELECT CONCAT(UPPER(SUBSTRING(visit_Status, 1, 1)), SUBSTRING(visit_Status FROM 2)) as Status, COUNT('x') AS Visits
FROM visits
WHERE visit_Date BETWEEN #startdate AND #enddate
GROUP BY visit_Status";
return sqlexecution(startdate, enddate, sql);
}
I am representing this data in stackcolumn chart.
if you want to represent in pie chart , you can change in code
public void DrawMembersvisits(Chart targetchartcontrol, DateTime startdate, DateTime enddate)
{
chart1 = targetchartcontrol;
Series series = null;
Title title;
string area = null;
chart1.ChartAreas.Clear();
chart1.Series.Clear();
chart1.Titles.Clear();
DataTable membervisits = null;
area = "Visits";
chart1.ChartAreas.Add(area);
series = chart1.Series.Add(area);
series.ChartArea = area;
title = chart1.Titles.Add("Member Visits");
title.Alignment = ContentAlignment.MiddleCenter;
title.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
title.DockedToChartArea = area;
chart1.Titles.Add("").DockedToChartArea = area;
foreach (Title titles in chart1.Titles)
{
titles.IsDockedInsideChartArea = false;
}
foreach (ChartArea areas in chart1.ChartAreas)
{
areas.Area3DStyle.Enable3D = true;
areas.AxisX.LabelStyle.IsEndLabelVisible = false; areas.AxisX.LabelStyle.Angle = -90;
areas.AxisX.LabelStyle.IsEndLabelVisible = true;
areas.AxisX.LabelStyle.Enabled = true;
}
foreach (Legend legends in chart1.Legends)
{
legends.Enabled = false;
}
foreach (Series serie in chart1.Series)
{
serie.ChartType = SeriesChartType.StackedColumn;
// change here to get the pie charts
// charttypes.ChartType = SeriesChartType.Pie;
// charttypes["LabelStyle"] = "Outside";
// charttypes["DoughnutRadius"] = "30";
// charttypes["PieDrawingStyle"] = "SoftEdge";
// charttypes.BackGradientStyle = GradientStyle.DiagonalLeft;
serie["LabelStyle"] = "Outside";
serie["ColumnDrawingStyle"] = "SoftEdge";
serie["LabelStyle"] = "Top";
serie.IsValueShownAsLabel = true;
serie.BackGradientStyle = GradientStyle.DiagonalLeft;
}
membervisits = visistsdataf.GetVisits(startdate, enddate);
chart1.Series[0].Points.DataBindXY(membervisits.Rows, "Status", membervisits.Rows, "Visits");
foreach (Series chartSeries in chart1.Series)
{
foreach (DataPoint point in chartSeries.Points)
{
switch (point.AxisLabel)
{
case "Accepted": point.Color = Color.Green; break;
case "Refused": point.Color = Color.Red; break;
}
point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);
}
}
}
Related
My goal is to create a chart that will sit inside of a panel restricting it's size.
I managed to achieve this some time ago but today I noticed that the chart was growing inside of the panel, not allowing the data to be seen.
I have attached a picture bellow which should help understand the issue.
UPDATE
I noticed that if I rmeove 'bottom' from the Anchor property of the panel the chart does not exceed the parent panel but it does not increase with the change of the form which is what I'm looking for.
I also noticed that there was also another chart on the form that was exceeding the parent form, this time the chart would extend to the right not allowing to see the data.
This is the code that generates this second chart and places is inside of the parent panel.
panel_chart.Controls.Clear();
chart1 = new Chart();
chart1.MouseMove += chart1_MouseMove;
chart1.ChartAreas.Add(new ChartArea("chartArea1"));
chart1.Series.Clear();
chart1.Titles.Clear();
var serieOEE = new Series("OEE");
serieOEE.ChartType = SeriesChartType.Line;
serieOEE.XValueType = ChartValueType.String;
var serieProd = new Series("Prod");
serieProd.ChartType = SeriesChartType.Column;
serieProd.XValueType = ChartValueType.String;
var serieDisp = new Series("Disp");
serieDisp.ChartType = SeriesChartType.Column;
serieDisp.XValueType = ChartValueType.String;
var serieQual = new Series("Qual");
serieQual.ChartType = SeriesChartType.Column;
serieQual.XValueType = ChartValueType.String;
DateTime DataReg = DateTime.MinValue;
List<AreaOEE> listaChart = new List<AreaOEE>();
foreach (var item in ListaGrafico) //listaOEE
{
if (item.Designacao == DesignacaoLista)
{
listaChart.Add(item);
}
}
listaChart = listaChart.OrderBy(a => a.IDReg).ToList();
DateTime DataUltimoReg = DateTime.MinValue;
int j = 0;
foreach (var item in listaChart)
{
string HoraGraf = Convert.ToDateTime(item.Hora).ToString("HH:mm");
if (j == 0 || j == listaChart.Count - 1 ||
Math.Abs(Convert.ToDateTime(item.Hora).Subtract(DataUltimoReg).TotalMinutes) >= 30)
{
serieOEE.Points.AddXY(HoraGraf, item.OEE);
serieProd.Points.AddXY(HoraGraf, item.Produtividade);
serieQual.Points.AddXY(HoraGraf, item.Qualidade);
serieDisp.Points.AddXY(HoraGraf, item.Disponibilidade);
DataUltimoReg = Convert.ToDateTime(item.Hora);
if (j == listaChart.Count - 2)
{
break;
}
}
j++;
}
//Adicionar o ultimo
foreach (var item in listaOEE)
{
if (item.Designacao == DesignacaoLista)
{
string sHora = "";
try
{
sHora = item.Hora.Substring(1, 5);
}
catch (Exception ex)
{
string sEx = ex.Message;
}
foreach (var itemOee in serieOEE.Points)
{
if (itemOee.AxisLabel == sHora)
{
itemOee.YValues[0] = item.OEE;
}
}
foreach (var itemP in serieProd.Points)
{
if (itemP.AxisLabel == sHora)
itemP.YValues[0] = item.Produtividade;
}
foreach (var itemD in serieDisp.Points)
{
if (itemD.AxisLabel == sHora)
itemD.YValues[0] = item.Disponibilidade;
}
foreach (var itemQ in serieQual.Points)
{
if (itemQ.AxisLabel == sHora)
itemQ.YValues[0] = item.Qualidade;
}
}
}
chart1.Series.Add(serieProd);
chart1.Series.Add(serieQual);
chart1.Series.Add(serieDisp);
chart1.Series.Add(serieOEE);
serieOEE.BorderWidth = 4;
chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 90;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 140;
chart1.Legends.Clear();
chart1.Legends.Add(serieOEE.Legend);
chart1.Titles.Add(DesignacaoLista + " " + DataTitulo.ToString("dd-MM HH:mm"));
chart1.Titles[0].Font = new Font("Arial", 13, FontStyle.Bold);
chart1.Visible = true;
chart1.Dock = DockStyle.Fill;
panel_chart.Controls.Add(chart1);
you can change the size of Chart with Chart.Size:
Chart1.Size = new Size(1000, 200); //1000px * 200px
I have a C# Windows Forms application in which there is a screen designed to show a Graph using the DataVisualization.Charting.Chart class where the X axis are composed of DateTime and the Y Axis are composed of integers (the goal is to represent the memory usage in MB over time of some other processes). So, I want to display this in a format of a Continuous function. But when I set the DataVisualization.Charting.Series object type to SeriesChartType.Line the Form plots the graph in a very strange way, see image below:
and when I set the object series type to SeriesChartType.Point the displayed graph is:
Notice that there are a lot of points that are in blank and that's ok because there aren't any registry of memory usage between those time intervals. The only problem I'm complaining here is that in the Line mode the graph is being plotted in this strange way. The code for the generation of these graphs is:
private void CarregaSerieMemoria()
{
// this InvokeRequired is because it is called in a separeted Thread, the graph creation happens in the Else block
if (this.InvokeRequired)
{
VoidVoidDelegate d = new VoidVoidDelegate(CarregaSerieMemoria);
this.Invoke(d);
}
else
{
try {
// Data table containing the Memory Usage history
foreach (DataRow row in Dados.dsComponentes.Tables["MemoryHistory"].Rows)
{
string proc = row["NomeProcesso"].ToString();
if (!string.IsNullOrEmpty(proc))
{
string dataStr = row["TimeStamp"].ToString();
string memoriaStr = row["Memoria"].ToString();
DateTime data;
int memoria;
try
{
data = DateTime.ParseExact(dataStr, "yyyyMMdd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
memoria = int.Parse(memoriaStr) / 1000;
}
catch (FormatException)
{
continue;
}
if (TemSerieProc(proc))
{ // if there is already a Series object with proc name
Series s = this.chartMemory.Series.Where(x => x.Name.Equals(proc)).FirstOrDefault();
s.Points.AddXY(data, memoria);
}
else
{ // else creates a new Series object and add this current point (data,memoria)
Series s = DefineNovaSerie(proc);
s.XValueType = ChartValueType.DateTime;
s.Points.AddXY(data, memoria);
this.chartMemory.Series.Add(s);
}
}
}
chartMemory.ChartAreas[0].AxisX.LabelStyle.Format = "dd/MM/yyyy HH:mm:ss";
chartMemory.ChartAreas[0].AxisX.Interval = 30;
chartMemory.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Minutes;
chartMemory.ChartAreas[0].AxisX.IntervalOffset = 1;
chartMemory.ChartAreas[0].AxisX.Minimum = graphDateBegin.ToOADate();
chartMemory.ChartAreas[0].AxisX.Maximum = graphDateEnd.AddHours(24).ToOADate();
chartMemory.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chartMemory.ChartAreas[0].AxisY.MajorGrid.LineWidth = 0;
chartMemory.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chartMemory.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
chartMemory.ChartAreas[0].AxisX.Title = "Horário";
chartMemory.ChartAreas[0].AxisY.Title = "Memória (MegaBytes)";
chartMemory.MouseWheel += chartMemory_MouseWheel;
chartMemory.MouseClick += chartMemory_MouseClick;
chartMemory.Visible = true;
labelLoad.Visible = false;
btnReload.Visible = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
private Series DefineNovaSerie(string proc)
{
Series temp = new Series(proc);
temp.ChartType = SeriesChartType.Line;
//temp.MarkerSize = 10;
temp.Color = GetNextColor(nextColorInt++);
return temp;
}
You populating chart from not ordered data. Your x axis is date so your data should be ordered by date when adding point to chart.
Here is an example (not tested) how you might fix the issue by sorting your data from datatable on TimeStamp field.
var dataTable = Dados.dsComponentes.Tables["MemoryHistory"];
var orderedDataView = new DataView(dataTable);
orderedDataView.Sort = "TimeStamp";
foreach (DataRow row in orderedDataView.ToTable().Rows)
{
//rest of code
}
I have 2 problems:
I want the names from the datatable but it is showing me in numeric form.
I would like a gap between the two bars but I can't find a way.
Here is the code:
private void InitializeGraph (DataTable poDt)
{
Telerik.Charting.ChartSeries chartseries = new Telerik.Charting.ChartSeries();
try
{
chartseries.Type = Telerik.Charting.ChartSeriesType.Bar;
Telerik.Charting.ChartSeriesItem csItem;
RadChart1.PlotArea.XAxis.AutoScale = true;
RadChart1.PlotArea.XAxis.DataLabelsColumn = "Name";
for (int iRow = 0; iRow < poDt.Rows.Count; iRow++)
{
chartseries = new Telerik.Charting.ChartSeries();
chartseries.Type = Telerik.Charting.ChartSeriesType.Bar;
chartseries.Name = poDt.Rows[iRow]["Name"].ToString().Trim();
csItem = new Telerik.Charting.ChartSeriesItem();
csItem.Name = poDt.Rows[iRow]["Name"].ToString();
csItem.Label.TextBlock.Text = poDt.Rows[iRow]["Value"].ToString();
RadChart1.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.True;
csItem.YValue = Int32.Parse(poDt.Rows[iRow]["Value"].ToString());
chartseries.AddItem(csItem);
RadChart1.Series.Add(chartseries);
}
RadChart1.PlotArea.XAxis.AddRange(1, poDt.Rows.Count, 1);
RadChart1.PlotArea.XAxis[poDt.Rows.Count].TextBlock.Text = chartseries.Name;
poDt.Rows.Count.ToString();
RadChart1.PlotArea.XAxis.AutoShrink = false;
RadChart1.PlotArea.XAxis.AutoShrink = true;
RadChart1.Series.Add(chartseries);
RadChart1.PlotArea.Appearance.Border.Visible = false;
RadChart1.Appearance.Border.Visible = true;
RadChart1.PlotArea.YAxis.IsLogarithmic = true;
RadChart1.PlotArea.YAxis.AutoScale = true;
RadChart1.PlotArea.YAxis.Appearance.ValueFormat=Telerik.Charting.Styles.ChartValueFormat.Number;
RadChart1.Appearance.BarWidthPercent = 50;
RadChart1.Chart.Appearance.FillStyle.MainColor = System.Drawing.Color.Red;
RadChart1.Chart.Appearance.FillStyle.MainColor = System.Drawing.Color.Transparent;
RadChart1.Legend.Appearance.FillStyle.MainColor = System.Drawing.Color.Transparent;
}
catch (Exception Ex)
{
//throw;
}
finally
{
poDt.Clear();
poDt = null;
chartseries = null;
}
}
Sorry, I do not believe there is a way to display two X-axis at the same time.
My suggestion is you use a CategoricalAxis for your X axis and create a custom bar chart that has a legend which differentiates the two values. I don't have any working samples, however you can use this Telerik Silverlight demo for starters.
Also, switch to RadChartView if you can. Because I would then suggest an easier approach, which is using a Categorical X-Axis and create multiple Y axes. If you go that route, you can do something like this for a DateTimeContinuous (or Categorical) X-axis with multiple Y-axes :
int count = 0;
LineSeries lineSeries = new LineSeries();
lineSeries.CategoryBinding = new PropertyNameDataPointBinding() { PropertyName = "TimeStamp" };
lineSeries.ValueBinding = new PropertyNameDataPointBinding() { PropertyName = "Value" };
lineSeries.VerticalAxis = new LinearAxis()
{
Title = "Title Here"
};
lineSeries.ItemsSource = yourCollection.Values;
//First Y-axis to be placed on the left of X-axis,
//additional Y-axes to be placed on right
if (count > 0 )
{
lineSeries.VerticalAxis.HorizontalLocation = Telerik.Charting.AxisHorizontalLocation.Right;
}
count++;
chartName.Series.Add(lineSeries);
Hope this helps.
I am working on creating a couple of charts and I cannot figure out why there is so much empty space on the left and right side of the chart. I have a Winforms Chart, ChartArea, and Series and there is always a good inch to the left and right side of the chart that seems like wasted space. What setting do I need to change to reduce the size of this empty space? I have included a screenshot of the chart with empty space with this post as well as the code that I use to create it. Thanks in advance.
if (listBoxCharts.SelectedItems.Count == 1)
{
switch (listBoxCharts.SelectedItem.ToString().Trim())
{
case "Incomplete Work Orders By Status":
ChartArea chartArea = new ChartArea();
Series series = new Series();
Title title = new Title();
chartArea.Area3DStyle.Enable3D = true;
chartArea.Area3DStyle.LightStyle = LightStyle.Realistic;
chartArea.Area3DStyle.Rotation = 10;
chartArea.Area3DStyle.WallWidth = 3;
chartArea.BorderColor = Color.Transparent;
chartArea.Name = "IncompleteWorkOrdersByStatus_ChartArea";
// Fix this hack
ChartContainer.ChartAreas.Clear();
this.ChartContainer.ChartAreas.Add(chartArea);
this.ChartContainer.Dock = DockStyle.Fill;
this.ChartContainer.Location = new Point(2, 21);
this.ChartContainer.Name = "Charts";
this.ChartContainer.PaletteCustomColors = new Color[] { Color.LemonChiffon };
series.ChartArea = "IncompleteWorkOrdersByStatus_ChartArea";
series.ChartType = SeriesChartType.StackedColumn;
series.CustomProperties = "DrawingStyle=Cylinder";
series.EmptyPointStyle.BorderDashStyle = ChartDashStyle.NotSet;
series.IsXValueIndexed = true;
series.Name = "IncompleteWorkOrdersByStatus_Series";
List<WorkOrder> incompleteWorkOrders = woDao.getIncompleteWorkOrders();
var uniqueStatuses = (
from statuses in incompleteWorkOrders
select statuses.fkOrderStatus).Distinct().ToList();
int xVal = 1;
foreach (var status in uniqueStatuses)
{
var count = (
from wo in incompleteWorkOrders
where wo.fkOrderStatus == status
select wo).Count();
DataPoint dPoint = new DataPoint(xVal, count);
if (status == null)
{
dPoint.AxisLabel = "No Status";
}
else
{
dPoint.AxisLabel = status.codedesc;
}
dPoint.ToolTip = count + " " + dPoint.AxisLabel;
series.Points.Add(dPoint);
xVal++;
}
this.ChartContainer.Series.Clear();
this.ChartContainer.Series.Add(series);
title.DockedToChartArea = "IncompleteWorkOrdersByStatus_ChartArea";
title.IsDockedInsideChartArea = false;
title.Name = "IncompleteWorkOrdersByStatus_Title";
title.Text = "Incomplete Work Orders By Status";
this.ChartContainer.Titles.Clear();
this.ChartContainer.Titles.Add(title);
break;
default:
break;
}
}
Try playing with the InnerPlotPosition settings:
chart1.ChartAreas[0].InnerPlotPosition.X = 0;
I'm currently building an application that shows a line-graph and uses MSChartControl.
Here is the relevant code:
WeatherDatabase _db = new WeatherDatabase(Properties.Settings.Default.SqlConnectionString);
private void AddSensorDataToGraph(int sensorType, string xTitle, string yTitle, string Title)
{
var sensorIdList = (from d in _db.Sensors where d.TypeId == sensorType select d.Id).ToArray();
var startDate = dateTimePickerStart.Value;
var stopDate = dateTimePickerStop.Value;
SetMaxMinValues(dateTimePickerStart.Value.ToOADate(), dateTimePickerStop.Value.ToOADate());
this.Text = chartValues.Titles["Titel"].Text = String.Format("{0} vom {1} bis {2}", Title, startDate, stopDate);
chartValues.ChartAreas[CHARTAREA].AxisX.Title = xTitle;
chartValues.ChartAreas[CHARTAREA].AxisY.Title = yTitle;
// Alte Datensätze löschen
chartValues.Series.Clear();
foreach (var sensorId in sensorIdList)
{
var values = (from d in _db.DeviceIO where d.IdSensor == sensorId && d.Timestamp > startDate && d.Timestamp < stopDate orderby d.Timestamp ascending select d).ToArray();
if (values.Length > 0)
{
var desc = values[0].Sensors.SensorType.Description;
chartValues.Series.Add(GenerateDefaultSeries(String.Format("{0}\r\nSensorId: {1}", desc, sensorId)));
//chartValues.Series.Add("Test" + sensorId);
int seriesId = chartValues.Series.Count - 1;
foreach (var item in values)
{
if (item.Value == null)
{
continue;
}
if ((double)item.Value == NOVALUE)
{
continue;
}
AddPointToChart((DateTime)item.Timestamp, (double)item.Value, seriesId);
}
}
}
}
private void AddPointToChart(DateTime timestamp, double value, int series)
{
DataPoint dataPoint = chartValues.Series[series].Points.Add(value);
dataPoint.XValue = timestamp.ToOADate();
dataPoint.AxisLabel = "dd.MM.yy hh:mm";
}
private void SetMaxMinValues(double min, double max)
{
if (min < max)
{
chartValues.ChartAreas[CHARTAREA].AxisX.Minimum = min;
chartValues.ChartAreas[CHARTAREA].AxisX.Maximum = max;
}
}
private Series GenerateDefaultSeries(string Name)
{
// Grundeinstellungen für die Data-Series setzen
Series series = new Series();
series.ChartType = SeriesChartType.Line;
series.Name = Name;
series.IsValueShownAsLabel = false;
series.IsVisibleInLegend = true;
series.IsXValueIndexed = false;
series.AxisLabel = "dd.MM.yy hh:mm";
// series.LabelFormat = "g";
series.XAxisType = AxisType.Primary;
series.XValueType = ChartValueType.Auto;
series.YValuesPerPoint = 1;
// series.AxisLabel = "dd.MM.yy hh:mm";
return series;
}
If i add a series in designer mode x-axies Labels are correct
Click for pic
But if i start my application and add a series programmatically it loks like this
Anyone knows why the x-axis caption / label is not displayed correctly?
EDIT:
Based on Tom's help I change some things:
var seriesName = String.Format("{0}\r\nSensorId: {1}", desc, sensorId);
var curSeries = chartValues.Series.Add(seriesName);
UpdateSeriesSettings(ref curSeries);
[...]
AddPointToChart((DateTime)item.Timestamp, (double)item.Value, curSeries);
[...]
private void UpdateSeriesSettings(ref Series series)
{
// Grundeinstellungen für die Data-Series setzen
// Series series = new Series();
series.ChartType = SeriesChartType.Spline;
series.IsValueShownAsLabel = false;
series.IsVisibleInLegend = true;
series.IsXValueIndexed = false;
series.AxisLabel = "dd.MM.yy hh:mm";
// series.LabelFormat = "g";
series.XAxisType = AxisType.Primary;
series.XValueType = ChartValueType.Auto;
series.YValuesPerPoint = 1;
// series.AxisLabel = "dd.MM.yy hh:mm";
}
But my X axis stil ain't having a label ):
Used the following code:
Fixed my problem.
var desc = values[0].Sensors.SensorType.Description;
var seriesName = String.Format("{0}\r\nSensorId: {1}", desc, sensorId);
curSeries = chartValues.Series.Add(seriesName);
curSeries.ChartType = SeriesChartType.Line;
curSeries.XValueType = ChartValueType.DateTime;
foreach (var item in values)
{
curSeries.Points.AddXY(item.Timestamp, item.Value);
}
It looks like you are adding each point as its own series. Usually, you would add many points into one series.
Do you intend to change seriesId right before you use it?
int seriesId = chartValues.Series.Count - 1;
This happens before you call AddPointToChart() so that is getting a different value than you used in the series
chartValues.Series.Add(GenerateDefaultSeries(String.Format("{0}\r\nSensorId: {1}", desc, sensorId)));
EDIT
The line chartValues.Series.Add(...) will return a variable of type Series which you can add to directly. see http://www.dotnetperls.com/chart
SensorID is your number and I think that there are no guarantees that the system will choose to populate its collection of Series in any particular order.
EDIT
It looks like you're adding your points to the series before you finish setting them up. Instead, set them all the way up, then add them:
private void AddPointToChart(DateTime timestamp, double value, int series)
{
DataPoint dataPoint = new DataPoint(timestamp.ToOADate(), value);
dataPoint.AxisLabel = "dd.MM.yy hh:mm"; // not sure how this will work, but try it.
chart1.Series[series].Points.Add(dataPoint );
}