- Define x (vector), y (vector), and z (matrix) values for a contourf plot. (If x and y are matrices, see note below)
- Randomly sample the x and y vectors.
- Using the randomly sampled x and y values, pull out the corresponding z data to create the text labels.
- Use text to add labels.
Is there any way to add a set of random punctual z values labels inside the plot using a contourf x, y, z command?
0 个评论
采纳的回答
10 个评论
更多回答(2 个)
5 个评论
Hi @MARCO BALESTRINI ,
To achieve your goal of adding labels that display the actual values of the Z variable at certain points on a contourf plot in MATLAB, you can use the ShowText option in combination with the LabelFormat property. Here is a step-by-step approach, start by defining your X, Y, and Z matrices. For example, using a mathematical function like peaks can serve as a good starting point:
[X, Y, Z] = peaks(50); % Create sample data
Use the contourf function to create the filled contour plot. You can specify levels if you want to control where the labels appear. For instance, to display contours at specified levels while showing text labels:
contourf(X, Y, Z, 'ShowText', 'on');
If you want to format the labels (for example, to show one decimal place), you can use the LabelFormat property. As of R2022b, this allows you to define how labels are displayed:
contourf(X, Y, Z, 'ShowText', true, 'LabelFormat', '%0.1f');
Here is complete example that combines all these steps:
% Create sample data [X, Y, Z] = peaks(50);
% Create filled contour plot with labeled contours contourf(X, Y, Z, 'ShowText', 'on', 'LabelFormat', '%0.1f'); colorbar; % Optional: adds a color bar for reference title('Filled Contour Plot with Labels'); xlabel('X-axis'); ylabel('Y-axis');
Now, if you are interested in showing labels in different units or applying custom formatting (like converting meters to feet), you can define a custom labeling function and pass it to LabelFormat. Here is an example function:
function labels = mylabelfun(vals) feetPerMeter = 3.28084; feet = round(vals * feetPerMeter); labels = vals + " m (" + feet + " ft)"; labels(vals == 0) = "0 m"; end
% Usage in contourf contourf(X, Y, Z, 'ShowText', true, 'LabelFormat', @mylabelfun);
Please see attached.
You can further enhance your plot's aesthetics by adjusting properties such as color maps (`colormap`), transparency (`FaceAlpha`), and line widths (`LineWidth`).
Hope this helps.
Please let me know if you have any further questions.
0 个评论
另请参阅
类别
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!