Adding data to geoscatter clicks

조회 수: 6 (최근 30일)
Maddie Long
Maddie Long 2022년 5월 13일
편집: Samya 2023년 7월 19일
Hi! I am using geoscatter to graph the counties in california. I would like the data when I click on the county display the county name and some other information as needed.
Is there a way to do this?
warning off
states = readgeotable('usastatehi.shp'); %
counties = shaperead('cb_2018_us_county_500k.shx'); %county shape file from cencus.gov
row = states.Name == 'California';
california = states(row,:);
% Extract the polygons in the .shp file
struct2poly = @(s) polyshape(s.X, s.Y);
p = arrayfun(struct2poly, states);
p2 = arrayfun(struct2poly, counties);
s = figure; hold on
geoshow(california)
plot(p)
plot(p2)

답변 (1개)

Samya
Samya 2023년 7월 19일
편집: Samya 2023년 7월 19일
Hi! To display additional information when clicking on a county in California, you can use the `datacursormode` function in MATLAB. Here's an example of how you can modify your code to achieve this:
% Load necessary shapefiles
states = readgeotable('usastatehi.shp');
counties = shaperead('cb_2018_us_county_500k.shx');
% Filter California state
row = states.Name == 'California';
california = states(row,:);
% Extract the polygons in the .shp file
struct2poly = @(s) polyshape(s.X, s.Y);
p = arrayfun(struct2poly, states);
p2 = arrayfun(struct2poly, counties);
% Plot the map
s = figure;
hold on
geoshow(california);
plot(p);
plot(p2);
% Enable data cursor mode
dcm_obj = datacursormode(s);
set(dcm_obj, 'UpdateFcn', @myUpdateFcn); % Set custom update function
Next, define the custom update function `myUpdateFcn` that will display the county name and other desired information when a county is clicked:
function txt = myUpdateFcn(~, event_obj)
% Get the clicked data point
pos = event_obj.Position;
% Find the corresponding county
county = counties(inpolygon(pos(1), pos(2), [counties.X], [counties.Y]));
% Extract desired information from the county structure
countyName = county.NAME; % Replace 'NAME' with the actual field name in the shapefile
% Construct the text to display
txt = {['County: ', countyName]};
end
Hope this helps!

카테고리

Help CenterFile Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by