- Home /
 
 
               Question by 
               Waltari · Jul 30, 2016 at 10:25 AM · 
                canvasuser interfacegraphstatistics  
              
 
              How to draw a 2D graph
I need to draw a graph for my decibel app that I am making with Unity. The solution below works but is not as exact as my employer would like. Could I make this graph look more professional and exact?
I was thinking about making a 2D texture and using SetPixel, but I am not sure if that is the correct way.
The graph is drawn on a canvas as part of an scalable UI.
 public class Graph : MonoBehaviour {
 
 public float graphWidth;
 public float graphHeight;
 LineRenderer newLineRenderer;
 List<int> decibels;
 int vertexAmount = 50;
 float xInterval;
 
     GameObject parentCanvas;
 
     // Use this for initialization
     void Start ()
     {
         parentCanvas = GameObject.Find("Canvas");
         graphWidth = transform.Find("Linerenderer").GetComponent<RectTransform>().rect.width;
         graphHeight = transform.Find("Linerenderer").GetComponent<RectTransform>().rect.height;
         newLineRenderer = GetComponentInChildren<LineRenderer>();
         newLineRenderer.SetVertexCount(vertexAmount);
 
         xInterval = graphWidth / vertexAmount;
     }
    
     //Display 1 minute of data or as much as there is.
     public void Draw(List<int> decibels)
     {
         if (decibels.Count == 0)
             return;
 
         float x = 0;
 
         for (int i = 0; i < vertexAmount && i < decibels.Count; i++)
         {
             int _index = decibels.Count - i - 1;
 
             float y = decibels[_index] * (graphHeight/130); //(Divide grapheight with the maximum value of decibels.
             x = i * xInterval;
 
             newLineRenderer.SetPosition(i, new Vector3(x - graphWidth / 2 , y - graphHeight / 2 , 0));
         }
     }
 }
 
              
               Comment
              
 
               
              Answer by TSantosFigueira · Jul 31, 2017 at 03:19 PM
I do believe you have a nice solution here, maybe drawing on each pixel will decrease the great performance you already have. What you could do to improve this, I think, is displaying the graph only on screen and show the axes, which could be defined by the user, something like velocity vs time, for example;
Your answer