How to make a graph in php. Create a pie chart. Creating a line graph using the GD library

There are two ways to create graphs in PHP. You can draw it yourself or use some library. I suggest learning how to create charts yourself. Firstly, because good libraries are paid. Secondly, when using any library, you are limited by its functionality. It's better to draw the graphs yourself.

First, let's look at the simplest option. There is an array containing the number of users who registered on the site in 5 days.

$mas = array(2, 7, 20, 9, 14);

Let's display this array on the page in the form of a graph. First, let's draw the coordinate axes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Comments:

3 - create an image

7, 8 - x and y axes

9-13 - notches on the x-axis

14-18 - numbers on the x axis

19, 20 - notches on the y-axis

21, 22 - numbers on the y axis

The drawing should look like this:

To draw a line on a graph, you need to find points on it along which the line will be drawn. In practice, you can immediately find a point and draw a line along it. But to make the example clearer, we will divide the problem into two parts. First, let's find all the points, then draw a graph based on them. To do this, we will create a two-dimensional array, which will contain the x and y coordinates of each point. To find coordinates, we need a reference point. This is the point at which the coordinate axes intersect. In our drawing it has coordinates x: 50, y: 250 pixels. To determine the position of each point, you need to use the scale of the graph. In the example, we set the scale ourselves. On the x-axis, 100 pixels are created for each day. The first day is 100 pixels away from the origin, the second is 200 pixels away, and so on. This means the x coordinate for the first day is 50 + 100 = 150. For the second, 50 + 200 = 250.

On the y-axis, 100 pixels are allocated for every 10 users. This means for one user - 10 pixels. It is necessary to take into account that the y-axis of the image is directed downward, which means that you do not need to add the value to the reference point, but subtract it. On the first day, 2 visitors registered on the site. The coordinate for this value is 250 - (2 * 10) = 230. For the second day, 250 - (7 * 10) = 180. Thus, the array with the coordinates of the points is as follows:

The graph looks like this:

We considered the simplest option for constructing a graph. I knew the number of days and the maximum number of users in advance. That's why I chose the scale of the graph myself. But usually this data can be different and the scale needs to be calculated. And the graph itself looks a little different. We are accustomed to the fact that the coordinate axes start from zero. But for ease of display, this rule is sometimes not observed. The x-axis does not start from 0, but from 1, so that there is no left of the line empty space. And the y-axis is shown so that all values ​​fit on the graph. For example, if the minimum value is 60 and the maximum value is 70, then the y-axis contains that range. Let's consider creating such a graph.

In the example, the x-axis is 570 pixels long. It needs to be divided into equal segments for each day. The x axis does not start from 0, but from 1. Therefore, there will be no segment between 0 and 1 and the number of segments becomes 1 less. If there are 5 days, then you get 4 segments. The formula for calculating the length of a segment is:

length = axis length / (number of days - 1)

The number may be a fraction, so the result must be rounded down.

570 - 50 is the length of the x axis. It depends on the size of the image.

We make the y axis such that all values ​​fit. You need to get the minimum and maximum values. They should occupy the entire height of the graph. Knowing the range, we can calculate how many pixels should correspond to one user on the graph.

range = maximum - minimum

length = axle length/range

The resulting number also needs to be rounded.

Creating a graphical visit counter

An important feature of working with the GD module is that the script that generates a new picture should not output anything other than the picture itself (that is, it should not contain calls to echo, printf and similar functions). Subsequently, the image generated by the PHP script is displayed by the browser by specifying the URL of this script as the data source, for example, .

Creating a new drawing in PHP begins with either creating a new blank "page" (canvas) for drawing, or by loading and modifying an existing image. But before you start the withdrawal process graphic information, you need to select its format ( MIME type) by calling the header(str) function. For example, for PNG format you need to use the following code:

header("Content-type: image/png");

Next, to create an area for drawing, you need to call the int imagecreate (int x_size, int y_size) function, to which you pass the width and height (in pixels) of the generated image as parameters x_size and y_size, respectively; the function will return the identifier of the created drawing area. If we want to take an existing picture as a basis, then, depending on its format, we need to call the imagepng, or imagejpeg, or imagegif function, passing the name of the image file as a parameter. To display text, there is a function int imagestring(int im, int font, int x, int y, string s, int col), which needs to be passed: drawing area identifier, font size (1-5), X coordinate of the beginning of the text, Y coordinate the beginning of the text, the text itself and the color of the text, respectively. To determine the color, a construction of the form is used

$white=ImageColorAllocate($im, 255, 255, 255)

The last three numeric parameters are the RGB components of the required color. But since it is somewhat irrational to specify them every time, you should create an include file with definitions of the primary colors colors.inc:

After we have drawn our image using GD, it needs to be displayed in the browser. To do this, depending on the format of the picture, you need to call one of the functions: imagepng(int im [, string filename]) or imagejpeg (int im [, string filename [, int quality]]), passing the picture identifier as a parameter. If you specify a file name in addition to the drawing area identifier, the image will be saved to disk under this name). After we have finished working with the drawing, we need to free up the memory it occupies. The function imagedestroy (int im) is used for this purpose. Let's look at working with these functions using an example.

First, let's create templates for the header and footer of the HTML document, which we will use in order not to clutter the PHP code with HTML constructs:





Working with graphics in php


Let's say we want to create a graphical visit counter and we have a template file into which we need to “add” the number of visits. It might look like this.

Then the script that puts visit data into the counter template may look like this (the visit count itself is omitted):

The script for displaying the counter could be like this:

The image will contain the entered text (Figure 4).

figure 4

I'll say a few words about other functions from the GD library designed for working with text. itringUp() displays text vertically; ImageChar() and ImageCharUp() output a single character; ImageFontHeight() and ImageFontWidth() return the height and width of the font. The last two functions are used in the following example, in which a line of text is underlined with a line (the ImageLine function draws lines at the given coordinates):

The result of the script is shown in Figure 5.

figure 5

What else can you draw?

Naturally, in addition to lines, you can draw other shapes using GD. In the following example, we will use the ImageFilledRectangle() function to display the French flag in the browser window. The function is designed to draw rectangles filled with a specific color. First, let's fill the entire drawing with white, and then draw red and blue rectangles:

In Figure 6 you can see the result of our work.

Figure 6

PHP allows you to draw other types of polygons. There is a function called ImagePolygon() for this purpose. The following example displays a pentagon. The following information is passed to this function as parameters (except for the image descriptor and line color): the number of vertices (in our case, five) and an array of coordinates of points that are vertices. The result of the script is shown in Figure 7.

Figure 7

The same script uses another function that was not mentioned earlier - ImageFillToBorder(). It is used to fill an area limited by a specific color (in our case, the blue line of the polygon).
The ImageArc() function can draw arcs and circles. Let me give you a small example (see Figure 8):

figure 8

By changing the values ​​of the $width and $height variables, you can draw ovals, and by changing the angles, you can display various kinds of arcs.

Using ready-made images

The GD library allows you not only to draw pictures, but also to use ready-made ones. Let's consider a very real situation: your company's in-house designer has developed the appearance of buttons for a website, and you need to place several buttons of the same design and captions on the page.
The GD library includes functions such as ImageCreateFromGIF(), ImageCreateFromJPEG() and ImageCreateFromPNG(). They will help in cases where you need to create a new image based on an existing one. Let us have a file button.gif (Figure 9), which contains an ingenious button design for the site. Below is the PHP code that makes ready-made buttons based on this file. Notice how the sizes of the button, font, and lines of text are used to calculate the position coordinates of the headings. Here, the value of the $caption variable is taken as a caption for the button, which is passed to the script from the outside:

figure 9

The iX() and iY() functions return the width and height of the image, respectively. There is also a Getiize() function that can be used to determine the size and type of an image.
By itself, the above script does not have much practical value, but it can be used in any HTML page via SSI or as described in the following code:


What have we changed?
  • Now, since we have several types of charts, the type of chart will be passed to us via $_GET. Same with $Month and $Hour and $Year;
  • Next, we create an array $MonthNames, which will contain the names of the months. Since the array starts at zero, the first element is null;
  • Now, depending on the type, the $Query, $ResultArray, $ChartHeading and $XAsixName variables are assigned in the switch. If $Type is not set, months will be displayed by default;
  • Next, we connect to the database, execute the request, copy the result into an array and generate the first part of the xml file;
  • Next, we generate the body of the XML file. Since the body depends on the chart type, we use switch again;
  • Months: everything is the same except for the link. Now it will be like this: newchart-xmlurl-get-data.php; newchart - indicates that we are creating a new chart, xmlurl - at what address to look for data. Everything that follows is part of the URL. Here is the full link to the month January: newchart-xmlurl-get-data.php?type=hourly&Year=2010&Month=1
  • Days: the same is true for the month, but the URL now contains information related to days;
  • Clock: if we don't want others to follow this chart, we simply don't set a URL for it;
  • At the very end, close the XML;

Save this file as get-data.php; Now open your browser and test the script. For example: http://localhost/fcdemo/get-data.php?year=2010

You should see something like this:

Test

We are now completely finished with the diagrams. To check the operation, go to http://localhost/fcdemo/demo.html

If you did everything correctly, you will see a Column3D diagram on the page. If you click on one of the columns, a new chart will open. And so on…

Conclusion

If you have carefully studied this lesson, then most likely you already have a general understanding of connected diagrams in PHP/MySQL. Exactly the same diagrams can be made for the following statistics:

  • Number of sales over a period of time;
  • How many times has your website stopped working?
  • Number of visitors to an individual page;

The structure of the diagram will be the same for any topic. Use some parameter to retrieve information from the database, then turn the response into XML and that’s it, the diagram is ready!

For more inspiration, you can visit this demo page. Thank you for your attention!