浮头导航网

专注编程技术分享的开发者社区

晴读(21):MATLAB图中图制作步骤_matlab 制图



分享兴趣,传播快乐,

增长见闻,留下美好。

亲爱的您,这里是LearingYard学苑!

今天小编为您带来“晴读(21):MATLAB图中图制作步骤”。

欢迎您的访问!

Share interest, spread happiness,

increase knowledge, and leave it beautiful.

Dear, this is the Learning Yard Academy!

Today, the editor brings the

"Qing Reading (21): Steps for Creating a Subplot in MATLAB".

Welcome to visit!




一、思维导图(Mind Map)


二、图中图简介(Introduction to Inset Plots)

在论文中,利用MATLAB制作图中图能够通过主图呈现数据的整体趋势与全局特征,同时借助嵌入的子图聚焦关键细节(如曲线交叉点、异常波动区域等),既保证了数据展示的完整性,又能突出核心信息,帮助读者快速理解研究重点与数据规律,有效提升论文图表的信息密度与表达精准度,使研究结果的呈现更具逻辑性和说服力。

In academic papers, creating inset plots using MATLAB allows the main plot to present the overall trends and global characteristics of data, while the embedded subplot can focus on key details (such as curve intersection points, abnormal fluctuation areas, etc.). This not only ensures the integrity of data display but also highlights core information, helping readers quickly understand the research focus and data patterns. It effectively improves the information density and expression accuracy of the paper's charts, making the presentation of research results more logical and persuasive.

三、具体指令(Specific Instructions)

1.生成并准备数据。创建用于绘图的基础数据,确保两条曲线有交叉点(图中图通常用于放大展示这类细节)。使用Lin space函数生成均匀分布的x轴数据,再通过三角函数生成两条曲线的y值。为了增加曲线交叉的可能性,这里将x范围设置为0到20(较宽范围),并调整了第二条曲线的相位和振幅。同时注意,数据点数量(1000)越多,曲线越平滑,后续查找交叉点也更精准。

1. Generate and prepare data. Create basic data for plotting, ensuring that the two curves have an intersection point (inset plots are usually used to zoom in on such details). Use the `linspace` function to generate evenly distributed x-axis data, then generate y-values for the two curves using trigonometric functions. To increase the possibility of curve intersection, set the x-range from 0 to 20 (a relatively wide range) here, and adjust the phase and amplitude of the second curve. Also, note that the more data points there are (1000), the smoother the curves will be, and the more accurate the subsequent search for intersection points will be.

2.绘制主图框架。通过创建主图形窗口并绘制两条基础曲线,视觉区分(线型、颜色、标记)让曲线清晰可辨。首先figure创建新窗口,设置背景为白色('Color','w');接着利用hold on保持当前图形,确保后续绘图不会覆盖已有内容;然后grid on添加网格线,便于观察数据趋势;再通过plot函数分别绘制两条曲线,通过参数设置差异化样式:曲线1:红色(r)实线(-)+ 圆圈标记(o),线宽1.5,标记大小6;曲线2:绿色(g)虚线(--)+ 叉号标记(x),线宽1.5,标记大小6;最后用DisplayName设置曲线名称,供后续图例使用。

2. Draw the main plot framework. Create a main figure window and plot two basic curves, with visual distinctions (line styles, colors, markers) to make the curves distinguishable. First, use `figure` to create a new window and set the background to white (`'Color'','w'). Then, use `hold on` to retain the current graph, ensuring that subsequent plots will not overwrite existing content. Next, use `grid on` to add grid lines for easier observation of data trends. Then, use the `plot` function to draw the two curves respectively, with differentiated styles set through parameters: Curve 1: red (`r`) solid line (`-`) + circle markers (`o`), line width 1.5, marker size 6; Curve 2: green (`g`) dashed line (`--`) + cross markers (`x`), line width 1.5, marker size 6. Finally, use `DisplayName` to set curve names for subsequent use in the legend.

3.添加主图基础标注。通过坐标轴标签和图例,让读者理解图形的物理意义和曲线含义。首先用x label和y label添加坐标轴标签,设置字体大小为12,明确标注坐标轴的物理意义(此处用“自定义单位” 表示可根据实际场景修改);然后用legend显示图例,'Location’, ‘best'表示让MATLAB自动选择最佳位置(避免遮挡曲线)。

3. Add basic annotations to the main plot. Help readers understand the physical meaning of the graph and the implications of the curves through axis labels and a legend. First, use `xlabel` and `ylabel` to add axis labels with a font size of 12, clearly indicating the physical meaning of the axes (here, "Custom Unit" is used to indicate that it can be modified according to actual scenarios). Then, use `legend` to display the legend, with 'Location', 'best' meaning that MATLAB will automatically select the optimal position (to avoid covering the curves).

4.精准查找曲线交叉点。通过曲线交点可以定位两条曲线的交叉点(图中图的核心展示对象),采用双重方法确保找到有效交叉点。交叉点是指两条曲线y 值相等的位置(y1=y2),有两种方法查找:首先是符号变化法(优先):计算两条曲线的差值cross diff = y1 - y2;当差值的符号发生变化时(从正变负或负变正),说明曲线在此处交叉;用diff(sign(cross diff)) ~= 0检测符号变化,find获取变化位置的索引。第二个方法是差值绝对值法(备用):若符号变化法未找到交叉点(可能因数据离散性导致),则通过判断差值绝对值小于0.1(允许微小误差)来查找近似交叉点。同时注意,如果仍未找到,抛出错误提示(需检查数据或调整条件)。

4. Precisely find the intersection point of the curves. The intersection point of two curves (the core display object of the inset plot) can be located through curve intersection, and a dual method is adopted to ensure that valid intersection points are found. An intersection point refers to the position where the y-values of the two curves are equal (y1 = y2). There are two methods to find it: First, the sign change method (priority): Calculate the difference between the two curves, cross_diff = y1 - y2. When the sign of the difference changes (from positive to negative or negative to positive), it indicates that the curves intersect here. Use diff(sign(cross_diff)) ~= 0 to detect the sign change, and find to obtain the index of the change position. Second, the absolute difference method (backup): If the sign change method fails to find an intersection point (possibly due to data discreteness), find approximate intersection points by judging that the absolute value of the difference is less than 0.1 (allowing for minor errors). At the same time, note that if no intersection point is found yet, an error prompt should be thrown (it is necessary to check the data or adjust the conditions).

5.在主图标记交叉点。通过在主图中明确标记交叉点,并显示其坐标,引导读者关注图中图的放大区域。首先用plot函数绘制交叉点标记:黑色(k)五角星(p),大小8,填充黑色(MarkerFaceColor','k'),使其在主图中醒目;然后用text函数添加坐标文本:在交叉点右侧0.5 个单位处显示坐标值(保留2 位小数),红色字体('Color','r'),大小10,便于识别。

5. Mark the intersection point on the main plot. Mark the intersection point on the main plot and display its coordinates to guide readers' attention to the enlarged area of the inset plot. First, use the `plot` function to draw the intersection marker: a black ('k') pentagram ('p') with size 8, filled in black (`'MarkerFaceColor','k'`), making it prominent on the main plot. Then, use the `text` function to add coordinate text: display the coordinate values (rounded to 2 decimal places) 0.5 units to the right of the intersection point, in red font ('Color‘, 'r') with size 10 for easy identification.

6.创建图中图(核心步骤)。通过在主图中嵌入一个子图,放大展示交叉点附近的细节,让局部趋势更清晰。第一步是创建子坐标轴。用axes函数创建子坐标轴,通过'Position'参数设置其在主图中的位置和大小,参数格式为[左边界, 下边界, 宽度, 高度],取值范围0~1(相对于主图的归一化坐标)。这里设置为右上角区域(左0.65,下0.6,宽0.25,高0.25),并开启hold on和box on(子图加边框)。

6. Create an inset plot (core step). Embed a subplot in the main plot to zoom in on details near the intersection point, making the local trend clearer. The first step is to create sub-coordinate axes. Use the `axes` function to create sub-coordinate axes, and set their position and size in the main plot through the 'Position' parameter. The parameter format is `[left boundary, bottom boundary, width, height]`, with values ranging from 0 to 1 (normalized coordinates relative to the main plot). Here, it is set to the upper right area (left 0.65, bottom 0.6, width 0.25, height 0.25), and enables `hold on` and `box on` (add a border to the subplot).

7.第二步提取交叉点附近的局部数据。从原始数据中筛选出交叉点前后1 个单位范围内的x 和y 值,确保子图仅展示交叉点附近的细节(避免包含过多无关数据)。

7. Step 2: Extract local data near the intersection point. Filter the x and y values within a range of 1 unit before and after the intersection point from the original data to ensure that the subplot only displays details near the intersection point (avoiding inclusion of excessive irrelevant data).

8.第三步在子图中绘制局部曲线。在子坐标轴中绘制局部数据,保持与主图一致的线型、颜色和标记(仅缩小标记大小和线宽),确保视觉一致性。

8. Step 3: Plot the local curve in the subplot. Plot the local data in the sub-coordinate axis, maintaining the same line style, color, and markers as the main plot (only reducing the marker size and line width) to ensure visual consistency.

9.第四步调整子图坐标轴范围。自动计算子图y轴的合理范围(包含所有局部数据并留0.1的余量),避免因数据范围过小导致图形压缩。若数据范围无效(如y min >=y max),则手动设置一个0.2的范围,确保子图可见。

9. Step 4: Adjust the axis range of the subplot. Automatically calculate a reasonable y-axis range for the subplot (including all local data with a 0.1 margin) to avoid graph compression caused by an excessively small data range. If the data range is invalid (e.g., y min ≥ y max), manually set a 0.2 range to ensure the subplot is visible.

10.第五步美化子图(隐藏刻度)。隐藏子图的x轴和y轴刻度('XTick', [], 'YTick', []),减少视觉干扰,让读者专注于曲线细节;同时缩小字体大小至8,使子图更紧凑。

10. Step 5: Enhance the subplot (hide ticks). Hide the x-axis and y-axis ticks of the subplot using ('XTick', [], 'YTick', []) to reduce visual interference, allowing readers to focus on curve details. Meanwhile, reduce the font size to 8 to make the subplot more compact.

11.第六步添加手动标注。可以允许用户在图形任意位置添加自定义文本,增强图形的说明性(如标注特定趋势或现象)。运行gtext函数后,点击图形中的目标位置,即可在该位置添加蓝色文本('Color', 'b'),字体大小10。

11. Step 6: Add manual annotations. Users can be allowed to add custom text at any position in the graph to enhance the explanatory nature of the graph (such as annotating specific trends or phenomena). After running the gtext function, click the target position in the graph, and blue text (with the parameter 'Color', 'b') with a font size of 10 will be added at that position.

12.第七步保存图像。将制作好的图形保存为高质量图片,便于报告、论文或演示使用。用print函数保存图像,参数'-dpng'指定格式为PNG,'-r300'设置分辨率为300dpi(高清),文件名命为'inset_plot_final.png'。

12. Step 7: Save the image. Save the completed graph as a high-quality image for use in reports, papers, or presentations. Use the print function to save the image, with the parameter '-dpng' specifying the format as PNG, '-r300' setting the resolution to 300 dpi (high definition), and the file name as 'inset_plot_final.png'.

13.最后交互验证数据。通过MATLAB的交互工具验证图形数据的准确性,确认交叉点等关键位置的坐标。在图形窗口工具栏中点击“数据提示”按钮,然后点击曲线上的任意点,即可显示该点的x、y坐标,验证是否与计算结果一致。

13. Finally, verify the data interactively. Use MATLAB's interactive tools to verify the accuracy of the graph data and confirm the coordinates of key positions such as intersection points. Click the "Data Tip" button in the toolbar of the figure window, then click any point on the curve, and the x and y coordinates of that point will be displayed to verify whether they are consistent with the calculation results.

四、注意事项(Notes for Attention)

1.确保交叉点为标量:查找交叉点时限定只取单个点(如用find函数加参数1),避免因交叉点是数组导致后续范围筛选时出现维度不兼容问题。

1. Ensuring the intersection point is a scalar: When finding the intersection point, restrict it to a single point (e.g., using the find function with parameter 1) to avoid dimension incompatibility issues during subsequent range screening caused by the intersection point being an array.

2.保证子图数据有效:提取图中图数据时,需检查数据是否为空,设置y轴范围时确保最小值小于最大值,可通过强制修正范围避免ylim报错。

2. Ensuring the validity of subplot data: When extracting data for the inset plot, it is necessary to check whether the data is empty. When setting the y-axis range, ensure that the minimum value is less than the maximum value. The range can be corrected forcibly to avoid errors in ylim.

3.维持样式一致性:图中图与主图使用相同的线型、标记和颜色,同时合理设置子图位置与大小,隐藏冗余刻度以增强可读性。

3. Maintaining style consistency: The inset plot and the main plot should use the same line styles, markers, and colors. Meanwhile, reasonably set the position and size of the subplot, and hide redundant scales to enhance readability.

今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

Please leave us a message.

And let us meet tomorrow.

I wish you a nice day!

文案hu

排版hu

审核yyz

翻译:谷歌翻译

参考资料:百度百科,ChatGPT,bilibili

本文由LearningYard学苑整理发出,如有侵权请在后台留言!

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言