I'm currently working on a project, in which I need to create a Polar Plot with dynamically generated data. I've managed to create a somewhat decent polar plot, but have not been able to create what is needed.
This is my Polar Plot
this is the code I used to set the offset in the middle:
public Form1()
{
InitializeComponent();
chart1.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;
chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisY.Minimum = -20;
chart1.ChartAreas[0].AxisY.MajorGrid.IntervalOffset = 15;
chart1.ChartAreas[0].AxisY.MajorGrid.Interval = 5;
chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Solid;
chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Solid;
}
I found some help here: How to displace the origin of the Y axis on a polar Mschart?
I got a example on how I'm trying to get the polar:
The finished example
I don't think you can make an axis start from anywhere but its minimum.
(The linked post only makes the labels start from a different value.)
So we'll have to help with a little bit of owner-drawing.
A few short references:
var ca = chart1.ChartAreas[0];
var ax = ca.AxisX;
var ay = ca.AxisY;
Now let's hide the y-axis:
ay.LineWidth = 0;
To draw the portion of the axis from the interval offset to the maximum we simply code the PostPaint event:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
// add references..
..
// then use values to calulate pixel coordinates..
int py1 = (int)ay.ValueToPixelPosition(ay.Minimum + ay.IntervalOffset);
int py2 = (int)ay.ValueToPixelPosition(ay.Maximum);
int px = (int)ax.ValueToPixelPosition(ax.Maximum - ax.Minimum);
// blue to make it stand out
e.ChartGraphics.Graphics.DrawLine(Pens.Blue, px, py1, px, py2);
}
Result:
Of course finding the right values for Interval, IntervalOffset, Minimum and Maximum is all up to you..
Update: If you want to have a full set of shortened x-axis gridlines you could do a lot of math or use a graphics transform. As usual the latter is so much easier..:
Graphics g = e.ChartGraphics.Graphics;
int pyc = (int)ay.ValueToPixelPosition(ay.Minimum); // y-center
for (int i = 0; i < 360 / ax.Interval; i++)
{
g.TranslateTransform(px, pyc);
g.RotateTransform((float)(i * ax.Interval));
g.TranslateTransform(-px, -pyc);
g.DrawLine(Pens.colorOfYourChoice, px, py1, px, py2);
g.ResetTransform();
}
After setting ax.Interval = 30; we get this result:
Related
This is my first project in c# and I'm trying to create plots from data.
I'm struggling with drawing minor and major grid lines and labels on a logarithmic scale.
I've set the scale to logarithmic, set the base to 10 and both major and minor intervals to 1, and it works great, however, the interval starts with the minimum value on scale, so for example if data starts at 30M (I'm dealing with frequencies) the next major tick is at 300M and 3G, which is not as it should be.
Is there a way to set major grid to 1, 10, 100 etc, independent of what data is displayed? i've tried changing intervals, base and offset but have not achieved much.
area.AxisX.IsLogarithmic = true;
area.AxisX.LogarithmBase = 10;
area.AxisX.Interval = 1;
//area.AxisX.IntervalOffset = 10000;
area.AxisX.IntervalAutoMode = IntervalAutoMode.FixedCount;
area.AxisX.MajorGrid.Enabled = true;
area.AxisX.MajorTickMark.Enabled = true;
area.AxisX.MinorGrid.Enabled = true;
area.AxisX.MinorGrid.Interval = 1;
area.AxisX.MinorTickMark.Enabled = true;
area.AxisX.MinorTickMark.Interval = 1;
area.AxisX.Minimum = minMaxXY[0]; // in this example 30 M
area.AxisX.Maximum = minMaxXY[1]; // in this example 1 G
here's the link to the current grid
https://ibb.co/3WkxLfc
Thank you for your time and answers!
Thanks to TaW replay I managed to get my program working.
Here is my solution using customLabels location to draw the grid lines.
private void Chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
if (e.Chart.ChartAreas.Count > 0) // I don't yet truly understand when this event occurs,
// so I got plenty of null references.
{
Graphics g = e.ChartGraphics.Graphics;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
Color minorGridColor = Color.Gainsboro;
ChartArea area = e.Chart.ChartAreas[0];
double aymin = area.AxisY.Minimum;
double aymax = area.AxisY.Maximum;
int y0 = (int)area.AxisY.ValueToPixelPosition(aymin);
int y1 = (int)area.AxisY.ValueToPixelPosition(aymax);
foreach (var label in chart1.ChartAreas[0].AxisX.CustomLabels)
{
double xposition = area.AxisX.ValueToPixelPosition(Math.Pow(10, label.FromPosition + 0.1));
if (xposition > area.AxisX.ValueToPixelPosition(minMaxXY[0]) && xposition < area.AxisX.ValueToPixelPosition(minMaxXY[1]))
//this prevents drawing of lines outside of the chart area
{
int x = (int)xposition;
using (Pen dashed_pen = new Pen(Color.FromArgb(10, 0, 0, 0), 1))
{
dashed_pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
g.DrawLine(dashed_pen, x, y0, x, y1);
}
}
}
}
}
I also found the CustomLabel.GridTicks Property, but for some reason it did not work.
I created a Line Chart control in Windows Forms.
I divided the ChartArea, AxisX into four intervals but I want to apply back color (unique color) to each interval.
Can someone help me on this?
You could paint those areas, but this would always show above all chart elements including grid and data points.
So, as NLindborn suggests, the best way are StripLines.
They are under all elements and will scale nicely.
Note that their properties are in data values, so you need to know the values, or rather the x-axis range, in your chart.
Here is complete code example using StripLines:
// set up the chart:
ChartArea ca = chart.ChartAreas[0];
chart.Series.Clear();
for (int i = 0; i < 5; i++)
{
Series s = chart.Series.Add("Series" + (i+1));
s.ChartType = SeriesChartType.Line;
s.BorderWidth = 2;
}
// add a few test data
for (int i = 0; i <= 360; i++)
{
chart.Series[0].Points.AddXY(i, Math.Sin(i * Math.PI / 180f));
chart.Series[1].Points.AddXY(i, Math.Cos(i * Math.PI / 180f));
chart.Series[2].Points.AddXY(i, Math.Sin(i * Math.PI / 90f));
chart.Series[3].Points.AddXY(i, Math.Cos(i * Math.PI / 90f));
chart.Series[4].Points.AddXY(i, Math.Sin(i * Math.PI / 30f));
}
// set up the chart area:
Axis ax = ca.AxisX;
ax.Minimum = 0;
ax.Maximum = 360;
ax.Interval = 30;
// a few semi-transparent colors
List<Color> colors = new List<Color>() { Color.FromArgb(64, Color.LightBlue),
Color.FromArgb(64, Color.LightSalmon), Color.FromArgb(64, Color.LightSeaGreen),
Color.FromArgb(64, Color.LightGoldenrodYellow)};
Now we are ready to create the StripLines:
// this is the width of the chart in values:
double hrange = ax.Maximum - ax.Minimum;
// now we create and add four striplines:
for (int i = 0; i < 4; i++)
{
StripLine sl = new StripLine();
sl.Interval = hrange; // no less than the range, so it won't repeat
sl.StripWidth = hrange / 4f; // width
sl.IntervalOffset = sl.StripWidth * i; // x-position
sl.BackColor = colors[i];
ax.StripLines.Add(sl);
}
Note that you will need to adapt the stripline data whenever you change the axis range!
Also note the StripLine use axis values.
Update:
One common issue is to move the striplines when zooming. Without a little help they will stick to the original positions. Codeing the AxisViewChanged will help, maybe like so:
For each of your striplines calculate an IntervalOffset; in the simplest case of the 1st one this should work:
chart1.ChartAreas[0].AxisX.StripLines[0].IntervalOffset =
chart1.Series[0].Points[0].XValue - e.NewPosition;
For the others add the correct multiple of the width as above!
AxisX into four intervals but I want to apply back color (unique color)
These intervals are created with colored StripLine(s). Either via code:
var stripLine = new System.Windows.Forms.DataVisualization.Charting.StripLine()
{
BackColor = Color.Blue,
IntervalOffset = 4, // This is where the stripline starts
StripWidth = 2 // And this is how long the interval is
};
chart1.ChartAreas[0].AxisX.StripLines.Add(stripLine);
You need to add data points for the interval to show.
Or, StripLines can also be added from VS design mode from (Properties) -> ChartAreas -> Select a ChartArea -> Axes -> Select the Axis you want it to show on -> StripLines, then Add StripLine. You have to set a BackColor, IntervalOffset and StripWidth for it to show. If you set StripLine.Interval it will repeat by that interval.
I have a 6300 * 5 array with:
Columns 1,2 = CIE data
Columns 3,4,5 = S R G B
How should I Draw this in MsChart?
You have several options:
Add DataPoints with Markers in the respective Colors
Add Annotations
Use one of the xxxPaint events
With only 6500 points you can't really fill the area by setting single pixels. So you better use a FillElipse call for each point.
If you use the Pre- or PostPaint event you will need to use the AxisX/Y methods ValueToPixelPosition for calculating the pixel coordinates from the CIE values.
In any case you set the Minimum and Maximum for both Axes.
Also you will need to calculate either the Markers' or the Annotations' or the ellipses' size from the chart's ClientSize to avoid ugly gaps in the colored area.
If you want to use DataPoints set the ChartType = Point and use this function for each of your data:
DataPoint Cie2DataPoint(float x, float y, float r, float g, float b)
{
var dp = new DataPoint(x, y);
dp.Color = Color.FromArgb((int)(256 * r), (int)(256 * g),(int)(256 * b));
dp.MarkerColor = dp.Color;
return dp;
}
Here are examples of helper function:
int MarkerSize(Chart chart, int count)
{
return Math.Max(chart.ClientSize.Width, chart.ClientSize.Height )/ count + 1
}
void Rescale(Chart chart)
{
Series s = chart3.Series[0];
s.MarkerSize = MarkerSize(chart3, (int)Math.Sqrt(s.Points.Count));
}
The former takes an estimate of how many plot points you expect per axis; you may need to experiment a little. The next one assumes the points are actually filling a square; also that you only have one ChartArea.
This should also be modified for your data!
We need to rescale the sizes when the Chart is resized:
private void chart3_Resize(object sender, EventArgs e)
{
Rescale (sender as Chart);
}
Here is an example of setting it up with a calculated set of data. You should loop over your list of data instead..:
Series s = chart3.Series[0];
s.ChartType = SeriesChartType.Point;
s.MarkerSize = 3;
for (int x = 0; x < 100; x++)
for (int y = 0; y < 100; y++)
{
s.Points.Add(Cie2DataPoint(x/100f, y/100f, x/100f, y/100f, (x+y)/200f));
}
ChartArea ca = chart3.ChartAreas[0];
ca.AxisX.Minimum = 0;
ca.AxisY.Minimum = 0;
ca.AxisX.Maximum = 1;
ca.AxisY.Maximum = 1;
ca.AxisX.Interval = 0.1f;
ca.AxisY.Interval = 0.1f;
ca.AxisX.LabelStyle.Format = "0.00";
ca.AxisY.LabelStyle.Format = "0.00";
Rescale(chart3);
Result:
After grabbing ~6k colors from a CIE color chart the result looks rather grainy but basically correct:
Note that you probably need to allow for the reversed y-axis somehow; I simply subtracted my y-values from 0.9f. Use your own numbers!
I'm working with the System.Windows.Forms.DataVisualization.Charting library of C# in Visual Studio.
Creating the graphs themselves is no problem, however, since I'm using SeriesChartType.StackedArea100 for my serieses (which always fills the vertical graph space 100%), the grid (X & Y) is completely covered by the graphs.
However, I want the X-grid to be above the graphs, so it's easier to see which point belongs to what.
Am I missing something obvious here?
Gridlines are always drawn under the DataPoints.
One option is to make the Colors of the DataPoints semi-transparent.
Here is an example:
chart1.ApplyPaletteColors(); // necessary to access the original colors
if (checkBox1.Checked)
{
foreach (Series s in chart1.Series) s.Color = Color.FromArgb(192, s.Color);
}
You can raise alpha to 224 and still see the lines.
Or you could owner-draw GridLines in one of the xxxPaint events; but that of course is a little more complicated. OK, a lot more..
The drawing itself is regular GDI+ drawing with DrawLine calls in two loops.
But to get the loops and the coordinates right you need to :
Make sure you know/control the Minimum, Maximum & Interval for the axes. If they are not set but still on their auto-values you need to find a way to get at them.
know the Rectangle of the InnerPlotPosition in pixels(!). See here for two functions that will help you !
Here is an example:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
if (checkBox1.Checked) return;
ChartArea ca = chart1.ChartAreas[0];
RectangleF ipar = InnerPlotPositionClientRectangle(chart1, ca);
Axis ax = ca.AxisX;
Axis ay = ca.AxisY;
Color gc = ax.MajorGrid.LineColor;
Pen pen = new Pen(gc);
double ix = ax.Interval == 0 ? 1 : ax.Interval; // best make sure to set..
double iy = ay.Interval == 0 ? 50 : ay.Interval; // ..the intervals!
for (double vx = ax.Minimum; vx <= ax.Maximum; vx+= ix)
{
int x = (int)ax.ValueToPixelPosition(vx) + 1;
e.ChartGraphics.Graphics.DrawLine(pen, x, ipar.Top, x, ipar.Bottom);
}
for (double vy = ay.Minimum; vy <= ay.Maximum; vy += iy)
{
int y = (int)ay.ValueToPixelPosition(vy) + 1;
e.ChartGraphics.Graphics.DrawLine(pen, ipar.Left, y, ipar.Right, y);
}
pen.Dispose();
}
You should disable the GridLines and maybe even make the the Axes transparent:
chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisX.LineColor = Color.Transparent;
chart1.ChartAreas[0].AxisY.LineColor = Color.Transparent;
I've been racking my brain trying to figure out how to animate an effect. This is related to a question I asked on math.stackexchange.com.
https://math.stackexchange.com/questions/91120/equal-division-of-rectangles-to-make-total/
As a side note, I didn't implement the drawing algorithm that was defined on the question above -- instead using my own in order to change the perspective to make it look more condensed.
I've been able to draw a stationary 3d style effect, but I am having trouble wrapping my brain around the logic to make the lines below look like they are coming towards you.
My code is as follows,
List<double> sizes = new List<double>();
private void Form1_Load(object sender, EventArgs e)
{
for (int y = 1; y < 10; y++)
{
double s = ((240 / 2) / y) / 4;
sizes.Add(s);
}
sizes.Add(0);
}
int offset = 0;
private void button1_Click(object sender, EventArgs e)
{
Bitmap b = new Bitmap(320, 480);
Graphics g = Graphics.FromImage(b);
Color firstColor = Color.DarkGray;
Color secondColor = Color.Gray;
Color c = firstColor;
int yOffset = 0;
for(int i = 0; i < sizes.Count; i++)
{
c = (i % 2 == 0) ? firstColor : secondColor;
int y = (int)Math.Round(b.Height - yOffset - sizes[i]);
int height = (int)Math.Round(sizes[i]);
g.FillRectangle(new SolidBrush(c), new Rectangle(0, y + offset, b.Width, height + offset));
yOffset += (int)sizes[i];
}
this.BackgroundImage = b;
offset+=1;
}
Each button click should cause the rectangles to resize and move closer. However, my rectangles aren't growing as they should. My logic draws fine, but simply doesn't work as far as moving goes.
So my question is:
Is there an existing algorithm for this effect that I am not aware of, or is this something pretty simple that I'm over thinking? Any help in correcting my logic or pointing me in the right direction would be very appreciated.
Interesting...
(video of the answer here: http://youtu.be/estq62yz7v0)
I would do it like that:
First, drop all RECTANGLE drawing and draw your effect line by line. Like so:
for (int y=start;y<end;y++)
{
color = DetermineColorFor(y-start);
DrawLine(left, y, right, y, color);
}
This is of course pseudo-code not to be troubled with GDI+ or something.
Everything is clear here, except on how to code DetermineColorFor() method. That method will have to return color of the line at specified PROJECTED height.
Now, on the picture, you have:
you point of view (X) - didn't know how to draw an eye
red line (that's your screen - projection plane)
your background (alternating stripes at the bottom)
and few projecting lines that should help you devise the DetermineColorFor() method
Hint - use triangle similarity to go from screen coordinates to 'bar' coordinates.
Next hint - when you are in 'bar' coordinates, use modulo operator to determine color.
I'll add more hints if needed, but it would be great if you solved this on your own.
I was somehow inspired by the question, and have created a code for the solution. Here it is:
int _offset = 0;
double period = 20.0;
private void timer1_Tick(object sender, EventArgs e)
{
for (int y = Height / 3; y < Height; y++)
{
using (Graphics g = CreateGraphics())
{
Pen p = new Pen(GetColorFor(y - Height / 3));
g.DrawLine(p, 0, y, Width, y);
p.Dispose();
}
}
_offset++;
}
private Color GetColorFor(int y)
{
double d = 10.0;
double h = 20.0;
double z = 0.0;
if (y != 0)
{
z = d * h / (double)y + _offset;
}
double l = 128 + 127 * Math.Sin(z * 2.0 * Math.PI / period);
return Color.FromArgb((int)l, (int)l, (int)l);
}
Experiment with:
d - distance from the eye to the projection screen
h - height of the eye from the 'bar'
period - stripe width on the 'bar'
I had a timer on the form and event properly hooked. Timer duration was 20ms.
Considering that you're talking here about 2D rendering, as much as I understodd, to me it seems that you're gonna to reenvent the wheel. Cause what you need, IMHO; is use Matrix Transformations already available in GDI+ for 2D rendering.
Example of aplying it in GDI+ : GDI+ and MatrixTranformations
For this they use System.Drawing.Drawing2D.Matrix class, which is inside Graphics.
The best ever 2D rendering framework I ever used is Piccolo2D framework which I used with great success in big real production project. Definitely use this for your 2D rendering projects, but first you need to study it little bit.
Hope this helps.