%% MLB visualization for player salary and injury status

% Copyright 2016 The MathWorks, Inc.

% Create stats connection object for salary data request
sBaseball = statsllc('gkfrq6fxabcehmn2yctrc6j5','qYR5abCQgc',...
                    'DataType','stats','LeagueAbbreviation','mlb',...
                    'Resource','salaries','SportName','baseball',...
                    'VersionNumber','v1');

% Request all player salary data for the current season
data = fetch(sBaseball);

% Get salary by player id
playerData = [data.apiResults.league.season.salaries.player];
salaryData = table((1:data.recordCount)',[playerData.playerId]',{playerData.firstName}',...
                   {playerData.lastName}',[data.apiResults.league.season.salaries.salary]',false(data.recordCount,1),...
                   'VariableNames',{'Record','PlayerId','FirstName','LastName','Salary','Injured'});

 
% Change Resource to participant for participant data request
pause(2) 
sBaseball.Resource = 'participants';

% Request all player demographic data for the current season
data = fetch(sBaseball);

% Match playerId in data sets
numPlayers = data.recordCount;
for i = 1:numPlayers
  playerId = data.apiResults.league.players{i}.playerId;
  salaryData.Injured(salaryData.PlayerId == playerId) = data.apiResults.league.players{i}.isInjured;
end

% Create scatter plot showing salary and injury status
sInjured = scatter(salaryData.Record(salaryData.Injured),salaryData.Salary(salaryData.Injured),'Marker','+','Linewidth',2);
hold on
sNotInjured = scatter(salaryData.Record(~salaryData.Injured),salaryData.Salary(~salaryData.Injured),'Marker','O','Linewidth',2);
hold off
sInjured.MarkerFaceColor = 'flat';
grid on

% Display plot information and legend
b = gca; 
title('Player Salary Comparison') 
xlabel('Record') 
ylabel('Salary') 
ytickformat(b,'usd') 
legend({'Player with Injury','Player Without Injury'},'Location','best') 