Как изменить цвет графиков в матлабе
Перейти к содержимому

Как изменить цвет графиков в матлабе

  • автор:

Как изменить цвет графиков в матлабе

  • 2-D line plot

Syntax

Description

Vector and Matrix Data

plot( X , Y ) creates a 2-D line plot of the data in Y versus the corresponding values in X .

To plot a set of coordinates connected by line segments, specify X and Y as vectors of the same length.

To plot multiple sets of coordinates on the same set of axes, specify at least one of X or Y as a matrix.

plot( X , Y , LineSpec ) creates the plot using the specified line style, marker, and color.

plot( X 1, Y 1. X n, Y n) plots multiple pairs of x— and y-coordinates on the same set of axes. Use this syntax as an alternative to specifying coordinates as matrices.

plot( X 1, Y 1, LineSpec 1. X n, Y n, LineSpec n) assigns specific line styles, markers, and colors to each xy pair. You can specify LineSpec for some xy pairs and omit it for others. For example, plot(X1,Y1,»o»,X2,Y2) specifies markers for the first xy pair but not for the second pair.

plot( Y ) plots Y against an implicit set of x-coordinates.

If Y is a vector, the x-coordinates range from 1 to length(Y) .

If Y is a matrix, the plot contains one line for each column in Y . The x-coordinates range from 1 to the number of rows in Y .

If Y contains complex numbers, MATLAB ® plots the imaginary part of Y versus the real part of Y . If you specify both X and Y , the imaginary part is ignored.

plot( Y , LineSpec ) plots Y using implicit x-coordinates, and specifies the line style, marker, and color.

Table Data

plot( tbl , xvar , yvar ) plots the variables xvar and yvar from the table tbl . To plot one data set, specify one variable for xvar and one variable for yvar . To plot multiple data sets, specify multiple variables for xvar , yvar , or both. If both arguments specify multiple variables, they must specify the same number of variables. (since R2022a)

plot( tbl , yvar ) plots the specified variable from the table against the row indices of the table. If the table is a timetable, the specified variable is plotted against the row times of the timetable. (since R2022a)

Additional Options

plot( ax , ___ ) displays the plot in the target axes. Specify the axes as the first argument in any of the previous syntaxes.

plot( ___ , Name,Value ) specifies Line properties using one or more name-value arguments. The properties apply to all the plotted lines. Specify the name-value arguments after all the arguments in any of the previous syntaxes. For a list of properties, see Line Properties .

p = plot( ___ ) returns a Line object or an array of Line objects. Use p to modify properties of the plot after creating it. For a list of properties, see Line Properties .

Examples

Create Line Plot

Create x as a vector of linearly spaced values between 0 and 2 π . Use an increment of π / 1 0 0 between the values. Create y as sine values of x . Create a line plot of the data.

Figure contains an axes object. The axes object contains an object of type line.

Plot Multiple Lines

Define x as 100 linearly spaced values between — 2 π and 2 π . Define y1 and y2 as sine and cosine values of x . Create a line plot of both sets of data.

Figure contains an axes object. The axes object contains 2 objects of type line.

Create Line Plot From Matrix

Define Y as the 4-by-4 matrix returned by the magic function.

Create a 2-D line plot of Y . MATLAB® plots each matrix column as a separate line.

Figure contains an axes object. The axes object contains 4 objects of type line.

Specify Line Style

Plot three sine curves with a small phase shift between each line. Use the default line style for the first line. Specify a dashed line style for the second line and a dotted line style for the third line.

Figure contains an axes object. The axes object contains 3 objects of type line.

MATLAB® cycles the line color through the default color order.

Specify Line Style, Color, and Marker

Plot three sine curves with a small phase shift between each line. Use a green line with no markers for the first sine curve. Use a blue dashed line with circle markers for the second sine curve. Use only cyan star markers for the third sine curve.

Figure contains an axes object. The axes object contains 3 objects of type line. One or more of the lines displays its values using only markers

Display Markers at Specific Data Points

Create a line plot and display markers at every fifth data point by specifying a marker symbol and setting the MarkerIndices property as a name-value pair.

Figure contains an axes object. The axes object contains an object of type line.

Specify Line Width, Marker Size, and Marker Color

Create a line plot and use the LineSpec option to specify a dashed green line with square markers. Use Name,Value pairs to specify the line width, marker size, and marker colors. Set the marker edge color to blue and set the marker face color using an RGB color value.

Figure contains an axes object. The axes object contains an object of type line.

Add Title and Axis Labels

Use the linspace function to define x as a vector of 150 values between 0 and 10. Define y as cosine values of x .

Create a 2-D line plot of the cosine curve. Change the line color to a shade of blue-green using an RGB color value. Add a title and axis labels to the graph using the title , xlabel , and ylabel functions.

Figure contains an axes object. The axes object with title 2-D Line Plot, xlabel x, ylabel cos(5x) contains an object of type line.

Plot Durations and Specify Tick Format

Define t as seven linearly spaced duration values between 0 and 3 minutes. Plot random data and specify the format of the duration tick marks using the ‘DurationTickFormat’ name-value pair argument.

Figure contains an axes object. The axes object contains an object of type line.

Plot Coordinates from a Table

A convenient way to plot data from a table is to pass the table to the plot function and specify the variables to plot.

Read weather.csv as a timetable tbl . Then display the first three rows of the table.

Plot the row times on the x -axis and the RainInchesPerMinute variable on the y -axis. When you plot data from a timetable, the row times are plotted on the x -axis by default. Thus, you do not need to specify the Time variable. Return the Line object as p . Notice that the axis labels match the variable names.

Figure contains an axes object. The axes object with xlabel Time, ylabel RainInchesPerMinute contains an object of type line.

To modify aspects of the line, set the LineStyle , Color , and Marker properties on the Line object. For example, change the line to a red dotted line with point markers.

Figure contains an axes object. The axes object with xlabel Time, ylabel RainInchesPerMinute contains an object of type line.

Plot Multiple Table Variables on One Axis

Read weather.csv as a timetable tbl , and display the first few rows of the table.

Plot the row times on the x -axis and the Temperature and PressureHg variables on the y -axis. When you plot data from a timetable, the row times are plotted on the x -axis by default. Thus, you do not need to specify the Time variable.

Add a legend. Notice that the legend labels match the variable names.

Figure contains an axes object. The axes object with xlabel Time contains 2 objects of type line.

Specify Axes for Line Plot

Starting in R2019b, you can display a tiling of plots using the tiledlayout and nexttile functions. Call the tiledlayout function to create a 2-by-1 tiled chart layout. Call the nexttile function to create an axes object and return the object as ax1 . Create the top plot by passing ax1 to the plot function. Add a title and y -axis label to the plot by passing the axes to the title and ylabel functions. Repeat the process to create the bottom plot.

Figure contains 2 axes objects. Axes object 1 with title Top Plot, ylabel sin(5x) contains an object of type line. Axes object 2 with title Bottom Plot, ylabel sin(15x) contains an object of type line.

Modify Lines After Creation

Define x as 100 linearly spaced values between — 2 π and 2 π . Define y1 and y2 as sine and cosine values of x . Create a line plot of both sets of data and return the two chart lines in p .

Figure contains an axes object. The axes object contains 2 objects of type line.

Change the line width of the first line to 2. Add star markers to the second line. Use dot notation to set properties.

Figure contains an axes object. The axes object contains 2 objects of type line.

Plot Circle

Plot a circle centered at the point (4,3) with a radius equal to 2. Use axis equal to use equal data units along each coordinate direction.

Figure contains an axes object. The axes object contains an object of type line.

Input Arguments

X — x-coordinates
scalar | vector | matrix

x-coordinates, specified as a scalar, vector, or matrix. The size and shape of X depends on the shape of your data and the type of plot you want to create. This table describes the most common situations.

Specify X and Y as scalars and include a marker. For example:

Specify X and Y as any combination of row or column vectors of the same length. For example:

Specify consecutive pairs of X and Y vectors. For example:

If all the sets share the same x— or y-coordinates, specify the shared coordinates as a vector and the other coordinates as a matrix. The length of the vector must match one of the dimensions of the matrix. For example:

Alternatively, specify X and Y as matrices of equal size. In this case, MATLAB plots each column of Y against the corresponding column of X . For example:

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration

Y — y-coordinates
scalar | vector | matrix

y-coordinates, specified as a scalar, vector, or matrix. The size and shape of Y depends on the shape of your data and the type of plot you want to create. This table describes the most common situations.

Specify X and Y as scalars and include a marker. For example:

Specify X and Y as any combination of row or column vectors of the same length. For example:

Alternatively, specify just the y-coordinates. For example:

Specify consecutive pairs of X and Y vectors. For example:

If all the sets share the same x— or y-coordinates, specify the shared coordinates as a vector and the other coordinates as a matrix. The length of the vector must match one of the dimensions of the matrix. For example:

Alternatively, specify X and Y as matrices of equal size. In this case, MATLAB plots each column of Y against the corresponding column of X . For example:

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration

LineSpec — Line style, marker, and color
string scalar | character vector

Line style, marker, and color, specified as a string scalar or character vector containing symbols. The symbols can appear in any order. You do not need to specify all three characteristics (line style, marker, and color). For example, if you omit the line style and specify the marker, then the plot shows only the marker and no line.

Example: «—or» is a red dashed line with circle markers.

Sample of solid line

Sample of dashed line

Sample of dotted line

Sample of dash-dotted line, with alternating dashes and dots

Sample of circle marker

Sample of plus sign marker

Sample of asterisk marker

Sample of point marker

Sample of cross marker

Sample of horizontal line marker

Sample of vertical line marker

Sample of square marker

Sample of diamond line marker

Sample of upward-pointing triangle marker

Sample of downward-pointing triangle marker

Sample of right-pointing triangle marker

Sample of left-pointing triangle marker

Sample of pentagram marker

Sample of hexagram marker

Sample of the color red

Sample of the color green

Sample of the color blue

Sample of the color cyan

Sample of the color magenta

Sample of the color yellow

Sample of the color black

Sample of the color white

tbl — Source table
table | timetable

Source table containing the data to plot, specified as a table or a timetable.

xvar — Table variables containing x-coordinates
string array | character vector | cell array | pattern | numeric scalar or vector | logical vector | vartype()

Table variables containing the x-coordinates, specified using one of the indexing schemes from the table.

A string, character vector, or cell array.

«A» or ‘A’ — A variable called A

[«A»,»B»] or <'A','B'>— Two variables called A and B

«Var»+digitsPattern(1) — Variables named «Var» followed by a single digit

An index number that refers to the location of a variable in the table.

A vector of numbers.

A logical vector. Typically, this vector is the same length as the number of variables, but you can omit trailing 0 or false values.

3 — The third variable from the table

[2 3] — The second and third variables from the table

[false false true] — The third variable

A vartype subscript that selects variables of a specified type.

vartype(«categorical») — All the variables containing categorical values

The table variables you specify can contain numeric, categorical, datetime, or duration values. If xvar and yvar both specify multiple variables, the number of variables must be the same.

Example: plot(tbl,[«x1″,»x2″],»y») specifies the table variables named x1 and x2 for the x-coordinates.

Example: plot(tbl,2,»y») specifies the second variable for the x-coordinates.

Example: plot(tbl,vartype(«numeric»),»y») specifies all numeric variables for the x-coordinates.

yvar — Table variables containing y-coordinates
string array | character vector | cell array | pattern | numeric scalar or vector | logical vector | vartype()

Table variables containing the y-coordinates, specified using one of the indexing schemes from the table.

A string, character vector, or cell array.

«A» or ‘A’ — A variable called A

[«A»,»B»] or <'A','B'>— Two variables called A and B

«Var»+digitsPattern(1) — Variables named «Var» followed by a single digit

An index number that refers to the location of a variable in the table.

A vector of numbers.

A logical vector. Typically, this vector is the same length as the number of variables, but you can omit trailing 0 or false values.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

3 — The third variable from the table

[2 3] — The second and third variables from the table

[false false true] — The third variable

A vartype subscript that selects variables of a specified type.

vartype(«categorical») — All the variables containing categorical values

The table variables you specify can contain numeric, categorical, datetime, or duration values. If xvar and yvar both specify multiple variables, the number of variables must be the same.

Example: plot(tbl,»x»,[«y1″,»y2»]) specifies the table variables named y1 and y2 for the y-coordinates.

Example: plot(tbl,»x»,2) specifies the second variable for the y-coordinates.

Example: plot(tbl,»x»,vartype(«numeric»)) specifies all numeric variables for the y-coordinates.

ax — Target axes
Axes object | PolarAxes object | GeographicAxes object

Target axes, specified as an Axes object, a PolarAxes object, or a GeographicAxes object. If you do not specify the axes, MATLAB plots into the current axes or it creates an Axes object if one does not exist.

To create a polar plot or geographic plot, specify ax as a PolarAxes or GeographicAxes object. Alternatively, call the polarplot or geoplot function.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1. NameN=ValueN , where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: plot([0 1],[2 3],LineWidth=2)

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: plot([0 1],[2 3],»LineWidth»,2)

Note

The properties listed here are only a subset. For a complete list, see Line Properties .

Color — Line color
[0 0.4470 0.7410] (default) | RGB triplet | hexadecimal color code | «r» | «g» | «b» | .

Line color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1] , for example, [0.4 0.6 0.7] .

A hexadecimal color code is a string scalar or character vector that starts with a hash symbol ( # ) followed by three or six hexadecimal digits, which can range from 0 to F . The values are not case sensitive. Therefore, the color codes «#FF8800» , «#ff8800» , «#F80» , and «#f80» are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Sample of the color red

Sample of the color green

Sample of the color blue

Sample of the color cyan

Sample of the color magenta

Sample of the color yellow

Sample of the color black

Sample of the color white

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: «blue»

Example: [0 0 1]

Example: «#0000FF»

LineStyle — Line style
«-» (default) | «—» | «:» | «-.» | «none»

Line style, specified as one of the options listed in this table.

Sample of solid line

Sample of dashed line

Sample of dotted line

Sample of dash-dotted line, with alternating dashes and dots

LineWidth — Line width
0.5 (default) | positive value

Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has markers, then the line width also affects the marker edges.

The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is less than the width of a pixel on your system, the line displays as one pixel wide.

Marker — Marker symbol
«none» (default) | «o» | «+» | «*» | «.» | .

Marker symbol, specified as one of the values listed in this table. By default, the object does not display markers. Specifying a marker symbol adds markers at each data point or vertex.

Sample of circle marker

Sample of plus sign marker

Sample of asterisk marker

Sample of point marker

Sample of cross marker

Sample of horizontal line marker

Sample of vertical line marker

Sample of square marker

Sample of diamond line marker

Sample of upward-pointing triangle marker

Sample of downward-pointing triangle marker

Sample of right-pointing triangle marker

Sample of left-pointing triangle marker

Sample of pentagram marker

Sample of hexagram marker

MarkerIndices — Indices of data points at which to display markers
1:length(YData) (default) | vector of positive integers | scalar positive integer

Indices of data points at which to display markers, specified as a vector of positive integers. If you do not specify the indices, then MATLAB displays a marker at every data point.

Note

To see the markers, you must also specify a marker symbol.

Example: plot(x,y,»-o»,»MarkerIndices»,[1 5 10]) displays a circle marker at the first, fifth, and tenth data points.

Example: plot(x,y,»-x»,»MarkerIndices»,1:3:length(y)) displays a cross marker every three data points.

Example: plot(x,y,»Marker»,»square»,»MarkerIndices»,5) displays one square marker at the fifth data point.

MarkerEdgeColor — Marker outline color
«auto» (default) | RGB triplet | hexadecimal color code | «r» | «g» | «b» | .

Marker outline color, specified as «auto» , an RGB triplet, a hexadecimal color code, a color name, or a short name. The default value of «auto» uses the same color as the Color property.

For a custom color, specify an RGB triplet or a hexadecimal color code.

An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1] , for example, [0.4 0.6 0.7] .

A hexadecimal color code is a string scalar or character vector that starts with a hash symbol ( # ) followed by three or six hexadecimal digits, which can range from 0 to F . The values are not case sensitive. Therefore, the color codes «#FF8800» , «#ff8800» , «#F80» , and «#f80» are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Sample of the color red

Sample of the color green

Sample of the color blue

Sample of the color cyan

Sample of the color magenta

Sample of the color yellow

Sample of the color black

Sample of the color white

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

MarkerFaceColor — Marker fill color
«none» (default) | «auto» | RGB triplet | hexadecimal color code | «r» | «g» | «b» | .

Marker fill color, specified as «auto» , an RGB triplet, a hexadecimal color code, a color name, or a short name. The «auto» option uses the same color as the Color property of the parent axes. If you specify «auto» and the axes plot box is invisible, the marker fill color is the color of the figure.

For a custom color, specify an RGB triplet or a hexadecimal color code.

An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1] , for example, [0.4 0.6 0.7] .

A hexadecimal color code is a string scalar or character vector that starts with a hash symbol ( # ) followed by three or six hexadecimal digits, which can range from 0 to F . The values are not case sensitive. Therefore, the color codes «#FF8800» , «#ff8800» , «#F80» , and «#f80» are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Sample of the color red

Sample of the color green

Sample of the color blue

Sample of the color cyan

Sample of the color magenta

Sample of the color yellow

Sample of the color black

Sample of the color white

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

MarkerSize — Marker size
6 (default) | positive value

Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.

DatetimeTickFormat — Format for datetime tick labels
character vector | string

Format for datetime tick labels, specified as the comma-separated pair consisting of «DatetimeTickFormat» and a character vector or string containing a date format. Use the letters A-Z and a-z to construct a custom format. These letters correspond to the Unicode ® Locale Data Markup Language (LDML) standard for dates. You can include non-ASCII letter characters such as a hyphen, space, or colon to separate the fields.

If you do not specify a value for «DatetimeTickFormat» , then plot automatically optimizes and updates the tick labels based on the axis limits.

Example: «DatetimeTickFormat»,»eeee, MMMM d, yyyy HH:mm:ss» displays a date and time such as Saturday, April 19, 2014 21:41:06 .

The following table shows several common display formats and examples of the formatted output for the date, Saturday, April 19, 2014 at 9:41:06 PM in New York City.

Value of DatetimeTickFormat Example
«yyyy-MM-dd» 2014-04-19
«dd/MM/yyyy» 19/04/2014
«dd.MM.yyyy» 19.04.2014
«yyyy年 MM月 dd日» 2014年 04月 19日
«MMMM d, yyyy» April 19, 2014
«eeee, MMMM d, yyyy HH:mm:ss» Saturday, April 19, 2014 21:41:06
«MMMM d, yyyy HH:mm:ss Z» April 19, 2014 21:41:06 -0400

For a complete list of valid letter identifiers, see the Format property for datetime arrays.

DatetimeTickFormat is not a chart line property. You must set the tick format using the name-value pair argument when creating a plot. Alternatively, set the format using the xtickformat and ytickformat functions.

The TickLabelFormat property of the datetime ruler stores the format.

DurationTickFormat — Format for duration tick labels
character vector | string

Format for duration tick labels, specified as the comma-separated pair consisting of «DurationTickFormat» and a character vector or string containing a duration format.

If you do not specify a value for «DurationTickFormat» , then plot automatically optimizes and updates the tick labels based on the axis limits.

To display a duration as a single number that includes a fractional part, for example, 1.234 hours, specify one of the values in this table.

Value of DurationTickFormat Description
«y» Number of exact fixed-length years. A fixed-length year is equal to 365.2425 days.
«d» Number of exact fixed-length days. A fixed-length day is equal to 24 hours.
«h» Number of hours
«m» Number of minutes
«s» Number of seconds

Example: «DurationTickFormat»,»d» displays duration values in terms of fixed-length days.

To display a duration in the form of a digital timer, specify one of these values.

In addition, you can display up to nine fractional second digits by appending up to nine S characters.

Example: «DurationTickFormat»,»hh:mm:ss.SSS» displays the milliseconds of a duration value to three digits.

DurationTickFormat is not a chart line property. You must set the tick format using the name-value pair argument when creating a plot. Alternatively, set the format using the xtickformat and ytickformat functions.

The TickLabelFormat property of the duration ruler stores the format.

Use NaN and Inf values to create breaks in the lines. For example, this code plots the first two elements, skips the third element, and draws another line using the last two elements:

plot uses colors and line styles based on the ColorOrder and LineStyleOrder properties of the axes. plot cycles through the colors with the first line style. Then, it cycles through the colors again with each additional line style.

You can change the colors and the line styles after plotting by setting the ColorOrder or LineStyleOrder properties on the axes. You can also call the colororder function to change the color order for all the axes in the figure. (since R2019b)

Цвета в Matlab — Как реализовать цвет и изменить стиль в Matlab?

В этой статье мы изучим цвета в Matlab. MATLAB или Matrix Laboratory — это язык программирования, разработанный MathWorks. Этот мощный язык находит свое применение в технических вычислениях. MATLAB предоставляет нам удобную среду, которую можно использовать для интеграции таких задач, как манипуляции с матрицей, построение графиков данных и функций, реализация алгоритмов, создание пользовательских интерфейсов и т. Д. MATLAB также удобен, поскольку предоставляет решения в форме, которую может легко сделать пользователь. Понимаю. Он использует математические обозначения для отображения решений.

Где мы можем использовать Matlab?

Ниже приведены несколько областей, где мы можем использовать Matlab:

  • вычисление
  • Разработка алгоритмов
  • моделирование
  • моделирование
  • макетирования
  • Анализ и визуализация данных
  • Научные Графики
  • Инженерная графика
  • Разработка приложений

MATLAB содержит ряд методов и функций для выполнения вышеупомянутых возможностей. Цель этой статьи — получить полное представление о цветах в MATLAB. Как следует из названия, назначение цветов в MATLAB — построить график функции с нужным цветом. Сначала мы используем функцию plot для создания графического представления наших данных, а затем мы используем специальный код для получения графика нужного цвета. Это просто и легко визуализировать тенденцию в данных, когда они наносятся на график, по сравнению с простым просмотром необработанных цифр, а цветовая кодировка делает их еще более привлекательными. Например, красный цвет может использоваться для отображения негативных тенденций в некоторых данных, а зеленый — для отображения позитивных тенденций. В этом случае просто сделать вывод, поскольку мы в основном ассоциируем красный цвет с опасностью или предостережением.

Какие цветовые коды используются в Matlab Plot?

Ниже приведен список некоторых букв, которые мы можем добавить в наш код, чтобы придать желаемый цвет нашему графику при построении в MATLAB.

  • б: синий
  • г: зеленый
  • р: красный
  • с: голубой
  • м: пурпурный
  • у: желтый
  • к: черный
  • ш: белый
Примеры реализации цветов в Matlab

Давайте теперь поймем использование некоторых из вышеупомянутых цветов:

Пример № 1

Сначала мы построим график и позволим MATLAB построить его с цветом по умолчанию:

Код:

X = -10 : 0.5 : 10;
Y = x. ^3 — x. ^2;
plot (x, y)

Вывод: вывод для этой функции по умолчанию будет синим, как показано на графике ниже.

Теперь давайте превратим это в цвета нашего желания.

Пример № 2

Чтобы преобразовать наш график в «КРАСНЫЙ» цвет, мы просто добавим «r» в наш код следующим образом:

Код:

X = -10 : 0.5 : 10;
Y = x. ^3 — x. ^2;
plot (x, y, ‘r’)

Вывод: Теперь вывод будет таким же, как указано выше, но на этот раз в «КРАСНОМ» цвете, как показано на графике ниже:

Пример № 3

Наконец, давайте попробуем это для ЖЕЛТОГО цвета. Итак, как объяснялось ранее, мы просто заменим ‘r’ в нашем коде на ‘y’ для желтого цвета.

Код:

X = -10 : 0.5 : 10;
Y = x. ^3 — x. ^2;
plot (x, y, ‘y’)

Выход:

Пример изменения стиля в Matlab

Кроме того, если мы хотим изменить стиль нашего графика, мы можем дополнительно настроить наш код, чтобы получить желаемый результат. Для этого мы подпишем цветную букву в нашем коде одним из следующих кодов, чтобы получить желаемый стиль:

  • , : Точка
  • о: круг
  • X: X-Mark
  • +: Плюс
  • с: площадь
  • *: Звезда
  • д: алмаз
  • v: треугольник (вниз)
  • ^: Треугольник (вверх)
  • <: Треугольник (слева)
Пример № 4

Мы будем использовать код, который мы использовали выше для красного цвета.

Код:

X = -10 : 0.5 : 10;
Y = x. ^3 — x. ^2;
plot (x, y, ‘r’)

Теперь давайте предположим, что нам нужно, чтобы наш график имел форму ромба, поэтому, как объяснено выше, мы будем индексировать «r» с помощью «d» (потому что код ромба — «d»). Наш окончательный код будет:

Код:

X = -10 : 0.5 : 10;
Y = x. ^3 — x. ^2;
plot (x, y, ‘dr’)

Выход:

Точно так же, если нам нужно иметь наш график в форме треугольников, обращенных вверх, мы подпишем или раскрасим код с помощью «^», который является кодом для обращенных вверх треугольников.

Код:

X = -10 : 0.5 : 10;
Y = x. ^3 — x. ^2;
plot (x, y, ‘^r’)

Выход:

Вывод

MATLAB как система использует массивы в качестве основного элемента данных. Вы должны быть знакомы с тем, что массивы не требуют каких-либо измерений, и, следовательно, позволяют MATLAB решать проблемы, связанные с вычислениями, особенно те, которые связаны с матрично-векторными формулировками с лучшей производительностью. В дополнение к своим вычислительным возможностям, MATLAB также предоставляет своим пользователям возможность рисовать и визуализировать данные для лучшего понимания и вывода выводов. Все эти возможности достигаются MATLAB за значительно меньшее время, когда его производительность сравнивается с неинтерактивным языком программирования, таким как C.

Рекомендуемые статьи

Это руководство по цветам в Matlab. Здесь мы обсудим, где и как использовать Цвета в Matlab с различными примерами, реализующими это. Вы также можете просмотреть другие наши статьи, чтобы узнать больше —

Setting the background color of a plot in MATLAB using the command line?

I am doing an assignment for my programming class, and I need to create a plot, along with a line of best fit for a few data points using only the command line in MATLAB. I know how to set the background using the figure editor, but I cannot for the life of me figure out how to do it via the command line. I need to set it to yellow. How would I do this? I think I am just missing something simple.

2 Answers 2

To change the background color of the axis:

To change the background color of the figure:

In general, if you want to know the properties of a plot, try

This will return a list of available property names and property values.

The solution to your specifiec question, is given by @M.Huster. I will just show you how you can help yourself in these cases.

Just make your plot and apply any manual changes you’d like. Then, in the figure window choose the option «Generate Code» in the File menu. This will generate an m-file that takes a dataset and recreates the figure for that dataset. If you look at that code (which is generally quite readable), you will see what commands are responsible for a certain effect.

MATLAB – Печать

Чтобы построить график функции, вам необходимо выполнить следующие шаги:

Определите x , указав диапазон значений для переменной x , для которой должна быть построена функция

Определите функцию, y = f (x)

Вызовите команду plot , как plot (x, y)

Определите x , указав диапазон значений для переменной x , для которой должна быть построена функция

Определите функцию, y = f (x)

Вызовите команду plot , как plot (x, y)

Следующий пример продемонстрирует концепцию. Построим простую функцию y = x для диапазона значений x от 0 до 100 с шагом 5.

Создайте файл сценария и введите следующий код –

Когда вы запускаете файл, MATLAB отображает следующий график –

Построение у = х

Давайте возьмем еще один пример для построения функции y = x 2 . В этом примере мы нарисуем два графика с одной и той же функцией, но во второй раз мы уменьшим значение приращения. Обратите внимание, что при уменьшении приращения график становится более плавным.

Создайте файл сценария и введите следующий код –

Когда вы запускаете файл, MATLAB отображает следующий график –

Построение у = х ^ 2

Немного измените файл кода, уменьшите приращение до 5 –

MATLAB рисует более плавный график –

Построение графика y = x ^ 2 с меньшим приращением

Добавление заголовка, меток, линий сетки и масштабирования на графике

MATLAB позволяет добавлять заголовки, метки вдоль осей X и Y, линии сетки, а также настраивать оси для улучшения графика.

Команды xlabel и ylabel генерируют метки вдоль оси x и оси y.

Команда title позволяет вам разместить заголовок на графике.

Команда grid on позволяет вам разместить линии сетки на графике.

Команда осевого равенства позволяет создать график с одинаковыми масштабными коэффициентами и пробелами на обеих осях.

Команда оси квадрат создает квадратный график.

Команды xlabel и ylabel генерируют метки вдоль оси x и оси y.

Команда title позволяет вам разместить заголовок на графике.

Команда grid on позволяет вам разместить линии сетки на графике.

Команда осевого равенства позволяет создать график с одинаковыми масштабными коэффициентами и пробелами на обеих осях.

Команда оси квадрат создает квадратный график.

пример

Создайте файл сценария и введите следующий код –

MATLAB создает следующий график –

Украсить наши графики

Рисование нескольких функций на одном графике

Вы можете нарисовать несколько графиков на одном графике. Следующий пример демонстрирует концепцию –

пример

Создайте файл сценария и введите следующий код –

MATLAB создает следующий график –

Несколько функций на одном графике

Установка цветов на графике

MATLAB предоставляет восемь основных вариантов цвета для рисования графиков. В следующей таблице приведены цвета и их коды –

Код цвет
вес белый
К черный
б синий
р красный
с Cyan
г зеленый
м фуксин
Y желтый

пример

Нарисуем график двух полиномов

f (x) = 3x 4 + 2x 3 + 7x 2 + 2x + 9 и

г (х) = 5х 3 + 9х + 2

f (x) = 3x 4 + 2x 3 + 7x 2 + 2x + 9 и

г (х) = 5х 3 + 9х + 2

Создайте файл сценария и введите следующий код –

Когда вы запускаете файл, MATLAB генерирует следующий график –

Цвета на графике

Настройка весов оси

Команда оси позволяет вам установить масштаб оси. Вы можете указать минимальное и максимальное значения для осей x и y, используя команду оси следующим образом:

Следующий пример показывает это –

пример

Создайте файл сценария и введите следующий код –

Когда вы запускаете файл, MATLAB генерирует следующий график –

Настройка весов оси

Генерация подзаговоров

Когда вы создаете массив графиков на одном и том же рисунке, каждый из этих графиков называется вложенным графиком. Команда subplot используется для создания подзаговоров.

Синтаксис для команды –

где, m и n – количество строк и столбцов массива графика, а p указывает, куда поместить конкретный график.

Каждый график, созданный командой subplot, может иметь свои характеристики. Следующий пример демонстрирует концепцию –

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *