MATLAB Examples

This is an example of how to create a graph plot in MATLAB®.

Read about the graph function in the MATLAB documentation. This function is available in R2015b or newer.

For more examples, go to MATLAB Plot Gallery

% Load location data
load CityLocationData LocData EdgeTable

% Create a graph object using the graph function
G = graph(EdgeTable,LocData);

% Visualize the graph object
p = plot(G,'EdgeLabel',G.Edges.Distance);
p.XData = G.Nodes.Lon;
p.YData = G.Nodes.Lat;

% Add labels and adjust limits
xlabel('Longitude')
ylabel('Latitude')
title('Distances (km) between locations in Boston')
axis equal
xlim([-71.14 -71.093])

% Add location names to plot
labelnames = strcat(num2str((1:8)'),':',cellstr(LocData.Station));
xl = xlim;
yl = ylim;
t = text(xl(1),yl(1),labelnames,'VerticalAlignment','top');

% Adjust text location
t.Position(2) = yl(1) + t.Extent(4);