Tag Archivio per: Plot



In the following article, we will explain how to use the MATLAB function xline() to create enhiesto lines and insert them into a graph. These types of lines are often used as markers in graphs and charts. Therefore, we will also show you how to add text labels to these lines so that you can fully master this function in MATLAB. We have also included practical examples with code snippets and images in this article to better explain how you can create or draw enhiesto lines in this powerful programming environment for scientific computing. We also review the input arguments and data types accepted by xline(). We will also explain how to use each of these arguments to specify the desired attributes for the line you want to create.

MATLAB xline Function Syntax

xline ( x )
xline ( x, LineSpec )
xline ( x, LineSpec, labels )

Description and Examples for MATLAB Function xline()

The MATLAB function xline() creates and draws enhiesto lines at a specified point on the x-axis of a graph. It also provides the ability to place text labels and specify the format and attributes of the line color, width, linetype, etc. of the line being created. Next, we will look at each input argument for this function and explain the function each of them performs.

x: Specifies the coordinate of the “x” axis from which to draw the enhiesto line. This input accepts scalars and vectors to specify the coordinates.

LineSpec: specifies the style and color attributes of the line. The data type that LineSpec accepts is a character vector or string scalar.

Labels: enters the text labels we want to add to the enhiesto line. This input accepts strings and cell arrays of character vectors.

How to Create a Derecho Line with the xline() Function in MATLAB

In this example, we will show you the simplest way to create a enhiesto line with MATLAB’s xline() function. For this, we will first create an empty axis and enable the grid with the following functions:

Now, we will draw a enhiesto line on this axis. To do this, we call the function xline() sending in “x” the coordinate of the x-axis on which we want to draw the line. In this case, in the middle of the axis, we enter in “x ” the value 0.5. In this example, we use only the “x” input argument, so the line style parameters take the default values. Thus, the line drawn by xline() will be continuous and black. Next, we see the full code. With these functions, we have created the following empty graph:

In the following figure we see the line drawn from the x-axis:

How to Create Multiple Derecho Lines with MATLAB xline() Function

The input “x” to the MATLAB function xline() accepts scalars and vectors. So, it is possible to draw multiple lines by sending to “x” a vector with the coordinates of the multiple lines you want to draw. Next, we will see an example where we send a coordinate vector to draw10 equidistant enhiesto lines on a graph.

How to Set the Color Style and Linetype Using the LinSpec Input of the MATLAB Function xline()

When we draw enhiesto lines with xline(), we have the option to specify the type and color of that line. This is done using the input “LineSpec”. In this example, we will see how to select these attributes. The syntax of the “LineSpec” input for selecting the line style and color is as follows:

‘linetype color’  =  ‘- – g’  =  Dashed line green

Below is a table of the different line types and color options for the LineSpec.

Next, we will see the color options offered by the xline() function.

Now, we use the “LineSpec” input to create a enhiesto line of the dash-dot line type in red color on the same graph we created in the previous example, this time at coordinate 0.2 of the x-axis. To do this, we send the following string in the “LineSpec” input to set these attributes:

Below we can see the code for this.

The following figure shows how the line style and line color attributes can be specified with the LinSpec input of the MATLAB function xline().

How to Add Text Labels to the Derecho Lines of a Plot with MATLAB’s xline() Function

In this example, we show you how to add text labels to the enhiesto lines we create with the xline() function. These labels are sent as character strings at the time of the function call in the “label” input of xline(). We will now see an example of how we create a solid continuous blue line with the label “LinuxHint”. Next, we will see how the input arguments of the xline() function should be sent to create lines with text labels.

In cases where multiple lines of labels need to be created, we must first create a cell array of character vectors with each of these labels in the appropriate order and send this array to the “label” input of the xline() function as in the following example.

Conclusion

In this article, we showed you how to create and draw a enhiesto line on a graph using the MATLAB function xline(). We have described each of the input arguments in detail so that you can fully master this function. We have also included practical examples with image code snippets, showing how to set the style of the enhiesto lines and how to add text labels to them. We hope you found this MATLAB article helpful. See other Linux Hint articles for more tips and information.



Source link


Python has a module named Seaborn that we may use to create statistical graphics or graphical representations of statistical data. This library is based on the matplotlib library’s principles and is closely linked to Pandas’ data models. When working with large amounts of data, we may want a nice graphical interface to see and analyze the data successfully. In this situation, we will require certain Python libraries, which is where Seaborn plays its role. The Seaborn is a graphical representation of our data, which is recorded as an array, collections, or even a whole DataFrame.

Seaborn allows you to save the outcome in various file formats, including.png,.pdf,.svg,.eps, and more. Let’s look at how to store the resulting graph in a specific file type.

In today’s data visualization article, we will show you how to save a Seaborn plot as a graphic file, which you can then include in a website, presentation, Excel spreadsheet, or another document. We will save it to an external file with the savefig() function. Within the function, we must define the filename, its format, and location.

Example 1: Loading the Sample Data for the Graph in Seaborn in Ubuntu 20.04

Initially, we loaded the Seaborn sample data titanic, which is built-in in Python Seaborn. For this, we have defined variable data and called a Seaborn load_dataset function. Within the load_dataset function, the data sample titanic is passed. We can easily read the titanic CSV file from the Python Seaborn. The print function has the variable data as an input, and the head function is applied to the provided data variable. The head function will return the first five entries inside the titanic dataset.

1
2
3
4
5

import seaborn as sns

data = sns.load_dataset(‘titanic’)

print(data.head())

The script is saved in the file save.py. When we run this file in the command prompt of Ubuntu. The following dataset is returned, which displays the head entries of the titanic dataset:

Example 2: Saving the Graph in the PNG Format in Seaborn in Ubuntu 20.04

Portable Network Graphic (PNG) is a raster picture file format. It can accommodate visuals with transparency or semi-transparent backgrounds. It’s a widely attractive file type among web designers. Because the PNG file format isn’t patented, anyone can open it with any editing software. We can save the plot in the .png extension in Seaborn Python.

In the example, we have a Seaborn module for plot rendering. Then, loaded the sample data titanic inside the Seaborn load_dataset function. We have created a variable scatterplot that has the Seaborn scatterplot function. The scatterplot function takes the pclass and fare column parameters from the data sample titanic and chooses the hue option sex for this plot. Inside the savefig() function, we have specified the filename and .png extension.

1
2
3
4
5
6
7
8
9
10
11

import seaborn as sns

data = sns.load_dataset(‘titanic’)

scatterPlot = sns.scatterplot(

    x=data[‘pclass’], y=data[‘fare’], hue=data[‘sex’])

fig = scatterPlot.get_figure()

fig.savefig(‘plot1.png’)

The plot figure is saved in the plot1.png file as displayed on the following screen:

Example 3: Saving the Graph in the SVG Format in Seaborn in Ubuntu 20.04

As in the previous example, the PNG extension is used to save the Seaborn plot figure. Now, we are using the SVG extension to save the figure of the plot. Vector files hold images using mathematical algorithms based on points and lines on a grid, unlike pixel-based raster formats like JPEGs, which are based on pixels. This implies that vector files, such as SVG, may be scaled up or down without losing quality, making them excellent for logos and intricate online images.

First, we have a dataset titanic, which we have loaded in the Seaborn load_dataset function. This sample dataset is stored inside the variable data. Then, we have another variable, myPlot, inside which we have a scatterPlot method, and, in that method, we have three inputs x, y, and hue. These inputs are set with the different columns of the data sample titanic. After this, we have the get_figure function from the myPlot variable, and through the savefig method, we have given a filename plot2 and .svg extension. The plot is now saved as plot2.svg file.

1
2
3
4
5
6
7
8
9
10
11

import seaborn as sns

data = sns.load_dataset(‘titanic’)

MyPlot = sns.scatterplot(

    x=data[‘class’], y=data[‘age’], hue=data[‘sex’])

Plot_fig = MyPlot.get_figure()

Plot_fig.savefig(‘plot2.svg’)

The plot is saved in the directory where your script file is saved. When you open that file plot2.svg, it visualizes the plot that we have rendered in the following figure:

Example 4: Saving the Graph in the PDF Format in Seaborn in Ubuntu 20.04

The PDF (Portable Document Format) enables the display of a variety of documents, including bank statements, presentations, and photographs, among other things. The fact that it’s a universal format means that the content of a PDF will always look the same on any device. Printers love it because it preserves the integrity of all page components and pixel density when widened. This example is quiebro different from the previous examples. We use the PDF format and then save the file in the directory where we want to save it.

As in the initial step, we have the dataset titanic which we have loaded by calling the load_dataset function of Seaborn and placing it inside the variable data. Then, we have a variable set_plot where the scatterPlot function takes the x, y, and hue arguments. Another variable, Figure, has gotten the figure from the scatterplot and saved it in the new specified directory as plot2.pdf.

1
2
3
4
5
6
7
8
9
10
11

import seaborn as sns

data = sns.load_dataset(‘titanic’)

set_plot = sns.scatterplot(

    x=data[‘pclass’], y=data[‘age’], hue=data[‘survived’])

Figure = set_plot.get_figure()

Figure.savefig(r‘/home/kalsoom/Documents/plot2.pdf’)

When we open the specified directory, the file is saved there as plot2.pdf. Opening the file shows the following plot:

Conclusion

Here, we have concluded the Seaborn save plot article. We can save the plot in Seaborn with different file extensions in the savefig method. We could save the plot as a.jpg,.pdf, or another file type. We have used several file extensions to save the plot figure with the savefig method. Finally, we utilized the savefig approach, which was simple method.



Source link


Time series is a type of data in which we see a set of measurements over a period. Every observation has its timestamp. Stock prices, sensor readings, program-observed data, and other types of data are examples of this type of data. In this tutorial, we will use the Seaborn and Pandas module to plot the time series analysis in Python. Before constructing a time series plot, let us examine a few concepts.

A time plot (also known as a statistical graph) shows values as they change over time. They’re like x-y graphs. However, time plots can only represent time on the x-axis. Whereas x-y graphs can plot various “x” variables, such as height, weight, and age. These plots do not include categories, unlike pie charts and bar charts. Time plots are useful in displaying the progression of data across time. For example, this type of chart might be useful if you were analyzing data at odd intervals.

Suppose we are plotting time plots with the Panda module. Pandas is a NumPy-based open-source library. A Python module provides numerous data structures and methods for processing numerical and statistical data. It’s most well-known for making data import and analysis significantly simpler. Pandas is quick, high-performing, and user-friendly.

Example 1: Creating a Simple Time Series Plot Using a Line Plot

We have used Python modules for constructing the time series plots. These modules include Seaborn, Pandas, and matplotlib modules. After adding these modules, we have created data by calling the Panda’s data frame function and inserted the field ‘Date’ for the x-axis and three more fields for the y-axis. The Date field has time-series data, and other fields have just random number lists.

Then, we have a Seaborn line plot function where the x and y variable parameters are set and pass the entire data frame inside it, which is stored inside a variable “df”. This line plot creates a time series plot, and we have defined the xticks location with the specified angle.

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

import matplotlib.pyplot as plt

import seaborn as sns

import pandas as pd

df = pd.DataFrame({‘Date’: [‘2021-04-01’, ‘2022-05-01’,
                            ‘2022-06-01’,‘2022-07-01’,
                 ‘2022-08-01’, ‘2022-09-01’,
                 ‘2022-10-01’, ‘2022-11-01’,
                 ‘2022-12-01’],
                   
                ‘A’: [35, 47, 18, 12, 11, 10, 31, 29, 62],
                ‘B’: [72, 66, 78, 13, 19, 25, 35, 45, 86],
                ‘C’: [23, 73, 82, 28, 62,87, 26, 45, 56],
                ‘D’: [22, 75, 26, 34, 15,14, 54, 25, 24]})
sns.lineplot(x = «Date», y = «A»,
            data = df)

plt.xticks(rotation = 20)

plt.show()

The times series plot is rendered inside the following figure. This figure is the single-column time series plot:

Example 2: Creating a Time Series Plot With Numerous Columns by Using a Line Plot

The preceding time series graph is rendered with a single column. Here, we have imported the Seaborn, Panda, and matplotlib modules for rendering the time series plot. Then, we have created data that has four fields defined. The first field is set with the dates and sets the name Date. In the other fields, we have set the car’s name, which shows the sales of the car on a specific date.

After that, we called the Seaborn line plot two times but with the different fields’ names. The x-axis is assigned with the field date, and the y-axis is assigned with the BMW and Detención field. We set the label for the y-axis and the tricks rotation for the x-axis with an angle of 20.

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
26
27
28

import matplotlib.pyplot as plt

import seaborn as sns

import pandas as pd

df = pd.DataFrame({‘Date’: [‘2021-04-01’, ‘2022-05-01’,

                            ‘2022-06-01’,‘2022-07-01’,
                 ‘2022-08-01’, ‘2022-09-01’,
                 ‘2022-10-01’, ‘2022-11-01’,
                 ‘2022-12-01’],
                 
                ‘BMW’: [14, 43, 24, 15, 45,14, 11, 25, 65],
                ‘Ferrai’: [42, 26, 88, 35, 75, 5, 15, 25, 82], 
                ‘Detención’: [19, 43, 62, 58, 52, 87, 36, 5, 26],
                ‘Civic’: [54, 15, 46, 15, 65, 24, 74, 15, 24]})

sns.lineplot(x = «Date», y = «BMW», data = df)

sns.lineplot(x = «Date», y = «Detención», data = df)

plt.ylabel(«BMW and Detención»)

plt.xticks(rotation = 20)

plt.show()

The time series plot is visualized with the multiple fields in the following graph figure:

Example 3: Create Multiple Time Series Plots Using a Line Plot

We can create multiple time series plots with several columns. Here, we have an example illustration where we have created the four time series plots with the line plot function. First, we have created data inside a variable represented by the name df. Then, we have created subplots for the time series graph, where we have also set the figure size inside the subplot function.

For each subplot, we have set the rotation of ticks. Within the line plot, we have assigned the columns for x and y parameters and set the color of each subplot by providing the color names. There is one additional parameter; tight_layout is set with the value that adjusts the padding of the subplots.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

import seaborn as sns

import pandas as pd

import matplotlib.pyplot as plt

df = pd.DataFrame({‘Date’: [‘2022-05-01’,‘2022-06-01’,

                            ‘2022-07-01’,‘2022-08-01’,
                            ‘2022-09-01’,‘2022-10-01’,
                            ‘2022-11-01’,‘2022-12-01’],
                   
                ‘col_A’: [47, 18, 12, 11, 10, 31, 29, 62],
                ‘col_B’: [66, 78, 13, 19, 25, 35, 45, 86],
                ‘col_C’: [73, 82, 28, 62,87, 26, 45, 56],
                ‘col_D’: [75, 26, 34, 15,14, 54, 25, 24]})

fig,ax = plt.subplots( 2, 2, figsize = ( 10, 6))

sns.lineplot( x = «Date», y = «col_A»,
            color = ‘g’, data = df,
            ax = ax[0][0])

ax[0][0].tick_params(labelrotation = 15)
sns.lineplot( x = «Date», y = «col_B»,
            color = ‘b’, data = df,
            ax = ax[0][1])

ax[0][1].tick_params(labelrotation = 15)
sns.lineplot(x = «Date», y = «col_C»,
            color = ‘r’, data = df,
            ax = ax[1][0])

ax[1][0].tick_params(labelrotation = 15)

sns.lineplot(x = «Date», y = «col_D»,
            color = ‘y’, data = df,
            ax = ax[1][1])

ax[1][1].tick_params(labelrotation = 15)

fig.tight_layout(pad = 1.25)

plt.show()


Here, we have multiple time series plot representations with the different columns and the different color lines by using the line plot.

Example 4: Create a Time Series Plot by Using a Bar Plot

The observed values are depicted in cuadrilongo bars using a bar plot. The Seaborn barplot() technique is used to construct bar graphs in Python’s Seaborn module. When displaying continuous time-series data, a bar plot can be utilized.

Then, we have set the data for the time series plot with the help of the Panda module function called a data frame. Inside the data frame, we set the dates and created a list of numbers representing the attendance percentage. With the to_datetime() function, we have set the date format for the time series plots. We have also defined the size of the figure of the time series plot. After that, we have a barplot() function that takes the values for the x and y parameters for the time series plot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

df = pd.DataFrame({«Date»: [‘01052022’,‘01062022’,‘01072022’,‘01082022’,

                             ‘01092022’,‘01102022’],
                   «Attendance»: [88,78,90,68,84,75]})

df[«Date»] = pd.to_datetime(df[«Date»], format = «%d%m%Y»)

plt.figure(figsize = (10,9))

sns.barplot(x = ‘Date’, y = ‘Attendance’,data = df)

plt.show()

For time-series data, the following graph provides an alternate visualization:

Conclusion

This is a basic rundown of how to generate time series plots for time-related input. When you have several data points in a specified time span, a time series plot is an excellent approach to represent your data. From creating a small dataset with Pandas Sequence to integrating a real-world dataset and plotting time series plots dependent on your needs, this article guides you through everything you need to know.



Source link